[英]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:
Intent
與來自app1的數據一起投入。 (看看PendingIntent
)。 BroadcastReceiver
,它將處理你的app1的Intents
。 onReceive
方法(在app2中)。 (把你的邏輯放在那里) 為了在不同的應用程序之間調用方法,你需要使用Intent
您無法直接從其他應用調用一個應用的方法。 相反,您必須從另一個活動調用一個活動並使用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.