问题
I have 2 android apps. Both are installed on the phone. Lets say the package name for the two are com.android.test1 and com.android.test2. How can i call the method Main2method() from the test1.Main class ?
Class for test1:
package com.android.test1;
import android.app.Activity;
import android.os.Bundle;
public class Main extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Class for test2:
package com.android.test2;
import android.app.Activity;
import android.os.Bundle;
public class Main2 extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public static void Main2method() {
//do something..
}
}
回答1:
Maybe you can broadcast an Intent to call it.
Intent it = new Intent("com.android.test2.Main2method");
context.sendBroadcast(it)
Make a BroadcastReceiver in com.android.test2.Main2 to receive the broadcast:
public class ActionReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("com.android.test2.Main2method".equalsIgnoreCase(intent.getAction())) {
Main2method();
}
}
}
Register the receiver in onCreate method of class Main1:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
receiver = new ActionReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.android.test2.Main2method");
registerReceiver(receiver, filter);
...
}
回答2:
If you want to send callbacks from app1 to app2:
- you should throw your own
Intentwith data from app1. (take look atPendingIntent). - into yout app2 you should register
BroadcastReceiverwhich will handle your app1'sIntents. - broadcastreceiver's
onReceivemethod (in app2) will be called each time when your Intent will be thrown by app1 and catched by app2. (put your logics there)
回答3:
in order to call method between different application you will need to use, Intent
also you will need intent-filter and BroadcastReceiver
回答4:
You cannot directly call a method of one app from another app. Instead, you have to invoke one activity from another and fetch result using Intent filters.
These links might help you
http://www.vogella.com/articles/AndroidIntent/article.html
http://saigeethamn.blogspot.in/2009/08/android-developer-tutorial-for_31.html
来源:https://stackoverflow.com/questions/12339083/android-call-method-from-another-app