根据文档 ,singleTask活动不能有多个实例。 我的应用程序的唯一活动是singleTask,它同时有2个实例。
重新创建问题的步骤
第1步
在Android Studio 3.3.1中创建一个新项目,添加无活动,将其命名为singleTaskBug(包com.example.singletaskbug ),使用最低API级别为21的Java语言,而不支持即时应用程序。
第2步
通过编辑手动添加一个新的活动AndroidManifest.xml然后创建一个新的Java类app ⯈ java ⯈ com.example.singletaskbug命名LauncherActivity 。
AndroidManifest.xml内容:
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">
android:name=".LauncherActivity"
android:excludeFromRecents="true"
android:launchMode="singleTask">
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' app'Shift F10 。
第四步
等到活动变得可见。 现在在测试设备上(在我的情况下为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.