簡體   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