【问题标题】:How to send a string between two own applications?如何在两个自己的应用程序之间发送字符串?
【发布时间】:2019-05-20 16:19:14
【问题描述】:

我有两个自己的应用程序,应用程序 A 和应用程序 B。 App A的一个activity,通过传递一个String打开App 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 中有一个按钮,当您单击该按钮时,您必须关闭应用程序 (finish ()) 并向应用程序 1 发送一个字符串。但不要从头打开 App1..

有什么想法吗?

提前谢谢你。

【问题讨论】:

  • 我不会为你提供完整的解决方案,但你要找的是广播接收器:developer.android.com/reference/android/content/… 基本上:1.你在 App1 广播接收器中注册 Intentfilter。 2. 在 App2 中,您使用要发送的字符串创建意图,您使用 context.sendBroadcast() 方法将此广播发送到您的 App1。

标签: android


【解决方案1】:

我认为您需要在应用 1 的 mainactivity 中覆盖方法 OnNewIntent,因为这是一个新意图而不是起始意图

【讨论】:

    【解决方案2】:

    您可以通过使用意图过滤器来实现此目的。在 manifest 中定义 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");
        }
    

    【讨论】:

    • 但是当我从应用程序 2 调用“startActivity”时,它会再次启动应用程序 1。
    • 是的,它将启动应用程序,您将登陆“App1Activity”。想要从 app2 启动哪个 Activity?
    • 如果在 manifest 中为 App1Activity 设置启动模式(singleTask/SingleTop 根据您的要求),它不会再次启动 Appliaction。如果你定义了,你会得到 App1Activity 的 OnNewIntent 上的数据。
    • 对不起!不要给我解释清楚。我的 app1 由 2 个活动组成:LoginActivity(初始)和 MainActivity(由 7 个片段组成)。我想从 MainActivity.Fragment01 启动另一个应用程序(App2)
    猜你喜欢
    • 2022-06-14
    • 2011-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多