如何使用putExtra打开另一个应用程序并为其发送一些数据? [英] How to use putExtra to open another app and send some data for it?
问题描述
我有两个应用程序(A,B),我想将它们链接在一起. 当用户使用应用程序A时,通过单击一个按钮,我要打开应用程序B并向其中发送一些数据.
I have two apps (A, B) that I want to link them together. When the user is in app A, by clicking on a button I want to open app B and send some data to it.
我在应用程序A中使用此方法去了应用程序B,并将一些数据发送到应用程序B:
I used this method in app A to go app B and send some data to app B:
public static boolean openApp(Context mContext, String packageName) {
PackageManager manager = context.getPackageManager();
Intent goToEncyclopedia = manager.getLaunchIntentForPackage(packageName);
if (goToEncyclopedia == null) {
return false;
}
goToEncyclopedia.addCategory(Intent.CATEGORY_LAUNCHER);
goToEncyclopedia.putExtra("NAME" , "Ehsan");
context.startActivity(goToEncyclopedia);
return true;
}
我在应用A中这样称呼它:
and I Call it like this in app A:
openApp(mContext, "encyclopedia.rasad.app.codenevisha.com.encyclopedia");
当我调用此方法时,它将打开应用程序B,但我要通过putExtra发送的数据将不会发送.
When I call this method it will open app B but data that I want to send with putExtra will not send.
这是我在App B中的代码,用于从Intent接收数据:
And this is my code in App B to receive data from intent:
Bundle bundle = getIntent().getExtras();
if (bundle != null){
String name = bundle.getString("NAME");
Log.i("EXTRAS", name);
}
推荐答案
在应用程序 B 中添加意图过滤器:
Add intent filter in app B:
<activity android:name=".MainActivity" android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.yourpackage.action" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
从应用程序 A 传递数据:
Intent intent = new Intent("com.yourpackage.action");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data","data string");
startActivity(intent);
从应用程序 B 中检索数据:
Retrieve data from app B:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getIntent().getStringExtra("data");
}
这篇关于如何使用putExtra打开另一个应用程序并为其发送一些数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!