Send plain text from an Android library to an Android project

冷暖自知 提交于 2019-12-10 11:28:29

问题


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?

Thank you.


回答1:


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).

For example, create an interface:

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

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.

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);
   }
}

Now let your activity implement 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.
   }
} 


来源:https://stackoverflow.com/questions/17912002/send-plain-text-from-an-android-library-to-an-android-project

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!