将纯文本从Android库发送到Android项目 [英] Send plain text from an Android library to an Android project

查看:59
本文介绍了将纯文本从Android库发送到Android项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从库中向项目android发送一些文本.它们是连接在一起的,我可以从项目中启动意图,但是我不了解如何将数据从库发送到主项目.我的问题:有可能吗?

I am trying to send some text from my library to the project android. They are connected, i can start an intent from the project but i dont understand how to send data from library to the main project. My question: is it possible?

谢谢.

推荐答案

您可以借助接口来实现这种通信.
这个想法是创建一个回调方法,该方法将在您的活动中实现,并由项目库调用以将文本发送回给您(在android项目中).

You could achieve this communication with the aid of interfaces.
The idea is to crate a callback method that will be implemented in your activity, and will be called by the project library to send text back to you (in android project).

例如,创建一个接口:

public interface OnTaskFinishedListener(){
   void onTaskFinished(String text);
}

让我们假设您的项目库中有一个名为Task的类,该类具有方法doTask(),您可以在Android项目中使用该类执行某些任务,然后将结果发送回给您.

Let assume that in your project library you have a class named Task with a method doTask() that you use in your Android project to perform some task and then send the result back to you.

然后Task的实现将如下所示:

Then the implementation of Task will look like this:

public class Task{
   // ......

   public void doTask(OnTaskFinishedListener listener){
      // Do the task...

      String textToSend = // some text to send to caller activity
      listener.onTaskFinished(textToSend);
   }
}

现在让您的活动实现OnTaskFinishedListner:

public class MainActivity extends Activity implements OnTaskFinishedListener{

   @Override
   public void onCreate(Bundle savedInstanceState){
       // .........
       Task task = new Task();
       task.doTask(this); //pass the current activity as the listener.
   }

   @Override
   public void onTaskFinished(String result){
      // do what you need to do with "result"
      // the method will be called when "doTask()" will finish its job.
   }
} 

这篇关于将纯文本从Android库发送到Android项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆