根据docs https://developer.android.com/guide/topics/manifest/activity-element#lmode,singleTask 活动不能有多个实例。我的应用程序的唯一活动是 singleTask,它同时有 2 个实例。
重现问题的步骤
Step 1
在Android Studio 3.3.1中新建一个项目,添加No Activity,命名为singleTaskBug,(包com.example.singletaskbug
),使用最低 API 级别 21 的 Java 语言,不支持即时应用程序。
Step 2
通过编辑手动添加新活动AndroidManifest.xml
然后创建一个新的Java类app
⯈ java
⯈ com.example.singletaskbug
named LauncherActivity
.
内容AndroidManifest.xml
:
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".LauncherActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.HOME" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
内容LauncherActivity.java
:
package com.example.singletaskbug;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
public class LauncherActivity extends Activity {
static int instanceCounter = 0;
final int instanceId;
final String TAG = "STB";
public LauncherActivity() {
instanceId = ++instanceCounter;
Log.d(TAG, "Constructed instance " + instanceId + ".");
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "Created instance " + instanceId + ".");
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d(TAG, "New intent to instance " + instanceId + ".");
}
@Override
protected void onDestroy() {
Log.d(TAG, "Destroyed instance " + instanceId + ".");
super.onDestroy();
}
}
Step 3
Go to Run
⯈ Edit Configurations...
and in the Launch Options
section set Launch:
to Specified Activity
, and Activity:
com.example.singletaskbug.LauncherActivity
, then click OK
, and Run 'app'
ShiftF10.
Step 4
等到活动变得可见。现在在测试设备(在我的例子中为 API 21)上,转到设置将此应用程序设置为默认启动器。然后按主页按钮。此时您将在 Logcat 中看到这一点:
02-15 17:22:01.906 26429-26429/com.example.singletaskbug D/STB: Constructed instance 1.
02-15 17:22:01.916 26429-26429/com.example.singletaskbug D/STB: Created instance 1.
02-15 17:22:24.228 26429-26429/com.example.singletaskbug D/STB: Constructed instance 2.
02-15 17:22:24.248 26429-26429/com.example.singletaskbug D/STB: Created instance 2.