SingleTask activity,但通过两个不同的应用程序打开

SingleTask activity, but opened through two different applications

这张图片对理解 启动模式 singleTask 提供的功能,取自 here

但是,我在同一应用程序的情况下理解这一点,我在理解时遇到问题 如果两个任务属于两个不同的应用程序怎么办

令人困惑的场景(虚构),

这次最主要的是,tasks/stacks属于两个不同的app

即使您使用 2 个不同的应用程序,它也可以在 expected way:

  • 如果您的 singleTask activity 已经存在,将使用该副本,并调用方法 onNewIntent()
  • 如果不存在,则正常启动

从技术上讲,从您的 link:

复制定义

The system creates a new task and instantiates the activity at the root of the new task. However, if an instance of the activity already exists in a separate task, the system routes the intent to the existing instance through a call to its onNewIntent() method, rather than creating a new instance. Only one instance of the activity can exist at a time.


这可以通过清单中的 making an activity a target for sharing textsingleTask 轻松验证:

    <activity
        android:name=".MainActivity"
        android:launchMode="singleTask">
        <intent-filter>
            <action android:name="android.intent.action.SEND" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="text/plain" />
        </intent-filter>
        <intent-filter>
            <action android:name="android.intent.action.SEND_MULTIPLE" />
            <category android:name="android.intent.category.DEFAULT" />
            <data android:mimeType="image/*" />
        </intent-filter>
    </activity>

现在向 onCreate()onNewIntent() 方法添加一些日志记录并进行一些场景测试。


我发现在测试各种启动模式时特别有用的是以下 ADB 命令:

  • adb dumpsys activity activities

这会输出大量文本(这可能有助于在执行此操作之前重新启动 phone - adb reboot)显示 activity 任务堆栈的详细信息。这可以用来向您展示您的 singleTask activity "rehomes" 本身是通过不同的应用程序启动的。


关于电子邮件的问题,我认为这取决于您使用的电子邮件客户端,但我希望他们能正确处理 onNewIntent() 方法,并在显示您的电子邮件之前保存当前草稿新电子邮件。