Android call method from another app

后端 未结 4 965
有刺的猬
有刺的猬 2020-12-08 23:56

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 M

4条回答
  •  轮回少年
    2020-12-09 00:21

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

提交回复
热议问题