首页 > 解决方案 > 如何在两个自己的应用程序之间发送字符串?

问题描述

我有两个自己的应用程序,应用程序 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..

有任何想法吗?

先感谢您。

标签: android

解决方案


您可以通过使用意图过滤器来实现这一点。在清单中定义 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");
    }

推荐阅读