来自另一个应用程序的Android调用方法

标签 android methods static package

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

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 来调用它。

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

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

public class ActionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("com.android.test2.Main2method".equalsIgnoreCase(intent.getAction())) {
            Main2method();
        } 
    }
}

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

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调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12339083/

相关文章:

android - Intent 的 OnDestroy()

android - ImageView 中设置的位图未填充父级

javascript - Meteor 模板助手不返回值

c++ - 由于使用静态变量导致的 undefined reference 错误

c++ - 返回函数局部变量作为引用

android - 对 onClickListeners 使用数据绑定(bind)时如何将 UI 数据传递给 ViewModel 函数?

使用 cordova cli 构建时的 Android installLocation

java - 如何重构银行方法中的循环

python - 使用python将对象 append 到列表是抛出对象内存地址而不是对象内部的数据

Java:何时将方法设为静态 v. 实例