使用singleTask活动时清除getIntent()数据

时间:2019-11-07 15:47:47

标签: android android-intent

我的应用可以使用“文件打开”意图接收新文件:

<activity android:launchMode="singleTask" >
    <intent-filter android:label="Text document" android:priority="1">
        <action android:name="android.intent.action.VIEW"/>
        <category android:name="android.intent.category.DEFAULT"/>
        <category android:name="android.intent.category.BROWSABLE" />
        <data android:scheme="content"/>
        <data android:scheme="file"/>
        <data android:host="*"/>
        <data android:mimeType="*/*"/>
        <data android:pathPattern=".*\\.txt"/>
    </intent-filter>
</activity>

实际数据通过onCreateonNewIntent方法处理:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // process intent data using getIntent().getData();
    // When the app is started from a file request then the intent contains the file data.

    // Settings the intent to some dummy data after processing to prevent getting the same data
    // when the task is brought back again from background does not work:
    setIntent(new Intent());
}

任务已经运行时,将其称为:

@Override
public void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // process intent data here using intent.getData();
}

除非从Android后台任务选择查看器(“最近的应用程序列表”)重新启动应用程序,否则所有这一切都将正常工作。每次从任务选择查看器启动应用程序时,getIntent().getData()都会重置为初始数据,这会使我的应用程序再次获得相同的文件数据。

更具体的是这些步骤:

  1. 通过单击* .txt文件启动应用程序。 onCreate获取文件信息。
  2. 按“后退”键退出应用。
  3. 显示Android任务查看器,然后单击我的应用程序的屏幕截图。 onCreate再次获得相同的文件信息。如何预防?

这里不会发生问题:

  1. 通过单击* .txt文件启动应用程序。 onCreate获取文件信息。
  2. 按“后退”键退出应用。
  3. 现在,我在Android启动器中单击应用程序的图标。 onCreate无法再次获取文件信息。这就是我想要的。

是否有一种方法可以清除getIntent()对象,以便在每次创建我的应用程序时都不会重置该对象?

此致

1 个答案:

答案 0 :(得分:1)

我找到了可行的解决方案:

if (((getIntent().getFlags() & Intent.FLAG_ACTIVITY_LAUNCHED_FROM_HISTORY)) == 0) {
  // process intent data
}
相关问题