【问题标题】:Android call method from another app来自另一个应用程序的 Android 调用方法
【发布时间】:2012-09-02 13:48:51
【问题描述】:

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

【问题讨论】:

  • 还需要在 test1 (app1) 中创建 ActionReceiver 类吗?

标签: android methods static package


【解决方案1】:

也许你可以广播一个 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);
    ...
}

【讨论】:

  • 问题:两个应用程序中都必须有 ActionReceiver 类吗?
  • 如何从另一个类 ActionReceiver 中的 test2 应用程序中的 Main2 类调用 Main2method();` 通常它无法识别它?
  • 还需要在 test1 (app1) 中创建 ActionReceiver 类吗?
【解决方案2】:

如果你想从 app1 向 app2 发送回调:

  1. 您应该使用来自 app1 的数据抛出您自己的 Intent。 (看看PendingIntent)。
  2. 您应该在您的 app2 中注册 BroadcastReceiver,它将处理您的 app1 的 Intents
  3. broadcastreceiver 的onReceive 方法(在app2 中)将在每次您的Intent 被app1 抛出并被app2 捕获时调用。 (把你的逻辑放在那里)

【讨论】:

    【解决方案3】:

    为了在不同的应用程序之间调用方法,你需要使用Intent

    你还需要intent-filterBroadcastReceiver

    【讨论】:

      【解决方案4】:

      您不能直接从另一个应用调用一个应用的方法。 相反,您必须从另一个活动中调用一个活动并使用 Intent 过滤器获取结果。

      这些链接可能对您有所帮助

      http://www.vogella.com/articles/AndroidIntent/article.html

      http://saigeethamn.blogspot.in/2009/08/android-developer-tutorial-for_31.html

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-07-13
        • 2019-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多