来自另一个应用程序的 Android 调用方法 [英] Android call method from another app

查看:26
本文介绍了来自另一个应用程序的 Android 调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 2 个安卓应用.两者都安装在手机上.假设两者的包名称是 com.android.test1 和 com.android.test2.我如何从 test1.Main 类调用方法 Main2method() ?

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 ?

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

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

推荐答案

也许你可以广播一个 Intent 来调用它.

Maybe you can broadcast an Intent to call it.

Intent it = new Intent("com.android.test2.Main2method");
context.sendBroadcast(it)

com.android.test2.Main2中创建一个BroadcastReceiver来接收广播:

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

Main1类的onCreate方法中注册接收者:

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

这篇关于来自另一个应用程序的 Android 调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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