android - 如何在两个自己的应用程序之间发送字符串?
问题描述
我有两个自己的应用程序,应用程序 A 和应用程序 B。应用程序 A 的一个活动,通过传递一个字符串打开应用程序 2。
代码 App1:
Intent launchIntent = getMainActivity().getPackageManager().getLaunchIntentForPackage("com.example.app2");
if (launchIntent != null)
{
launchIntent.setAction(Intent.ACTION_SEND);
launchIntent.putExtra("stringApp1ToApp2", "myString");
launchIntent.setType("text/plain");
startActivity(launchIntent);
}
代码 App2:
Bundle parameters = this.getIntent().getExtras();
if(parameters != null)
{
String b = parameters.getString("stringApp1ToApp2", "stringDefault");
}
工作正常。
我的问题是当我想将字符串从 App2 发送到 App1 时。在应用程序 2 中有一个按钮,当您单击该按钮时,您必须关闭应用程序(完成())并向应用程序 1 发送一个字符串。但不要从头开始打开 App1..
有任何想法吗?
先感谢您。
解决方案
您可以通过使用意图过滤器来实现这一点。在清单中定义 app1 的 Activity,如下所示。
<activity
android:name=".App1Activity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<data
android:host="send_data"
android:scheme="app1" />
</intent-filter>
</activity>
您可以使用从 app2 启动 App1Activity
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("app1://send_data?string_App2_To_App1=myString"));
try {
startActivity(intent);
} catch (e: Exception) {
Util.showToast(this, "Activity not found");
}
现在您可以使用 Activity App1Activity 的 onCreate/onNewIntent() 中的代码获取 app2 发送到 app1 的数据
Intent intent = getIntent();
Uri data = intent.getData();
if (data != null) {
String stringFromApp2 = data.getQueryParameter("string_App2_To_App1");
}
推荐阅读
- php - 尝试在表中插入值时所有值都被清除
- assembly - 当 esp 不是非常低时,汇编程序函数不执行
- php - 如何使用 PHP 两次显示相同的 MySQL 查询?
- reactjs - React 测试库:测试属性/prop
- python - 错误“布尔”对象没有属性“find_element_by_id”
- c - 试图调整 sscanf() 以忽略 \n 和 \t
- macos - 如何在 macOS 上以编程方式获取当前工作区
- php - 使用三元运算符处理多个语句
- winforms - 在 Visual Basic 窗体应用程序中使用 GoTo
- git - Git为远程添加不同的别名/昵称关于获取和推送