As per the docs, singleTask activities can't have multiple instances. The only activity of my app is singleTask, and it has 2 instances at the same time.
Steps to recreate the issue
Step 1
Create a new project in Android Studio 3.3.1, Add No Activity, name it singleTaskBug, (package com.example.singletaskbug
), using Java language with minimum API level 21 without support for instant apps.
Step 2
Add a new activity manually by editing AndroidManifest.xml
then creating a new Java Class in app
⯈ java
⯈ com.example.singletaskbug
named LauncherActivity
.
Content of 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>
Content of 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
Wait until the activity becomes visible. Now on the test device (API 21 in my case), go to settings to set this app as the default launcher. Then press the home button. At this point you'll see this in 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.
来源:https://stackoverflow.com/questions/54712162/what-makes-a-singletask-activity-have-2-instances