繁体   English   中英

来自其他应用的Android通话方法

[英]Android call method from another app

我有2个Android应用程序。 两者都安装在手机上。 让我们说两者的包名是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);
    ...
}

如果要将回调从app1发送到app2:

  1. 你应该把你自己的Intent与来自app1的数据一起投入。 (看看PendingIntent )。
  2. 进入你的app2你应该注册BroadcastReceiver ,它将处理你的app1的Intents
  3. 每当你的意图被app1抛出并被app2捕获时,都会调用broadcastreceiver的onReceive方法(在app2中)。 (把你的逻辑放在那里)

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

你还需要intent-filterBroadcastReceiver

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

这些链接可能会帮助您

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM