根据docs, singleTask 活动不能有多个实例。我的应用程序的唯一活动是 singleTask,它同时有 2 个实例。
重新创建问题的步骤
步骤1
在 Android Studio 3.3.1 中创建一个新项目,添加无活动,将其命名为 singleTaskBug,(包com.example.singletaskbug
),使用 Java 语言,最低 API 级别为 21,不支持即时应用程序。
第2步
通过编辑手动添加一个新活动,然后在⯈ ⯈AndroidManifest.xml
中创建一个新的 Java 类,命名为。app
java
com.example.singletaskbug
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();
}
}
第 3 步
转到Run
⯈Edit Configurations...
并在Launch Options
设置Launch:
为Specified Activity
、 和的部分中Activity:
com.example.singletaskbug.LauncherActivity
,然后单击OK
、 和Run 'app'
ShiftF10。
第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.