问题
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