我有这个最小化的应用程序。
MainActivity.java
public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); public void onNewIntent(Intent intent){ super.onNewIntent(intent);活动B.java
public class ActivityB extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
AndroidManifest.xml
<activity
android:name=".activities.MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:theme="@style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="*/*" />
<data android:mimeType="audio/*" />
</intent-filter>
</activity>
<activity
android:name=".activities.ActivityB"
android:exported="false"
android:parentActivityName=".activities.MainActivity"
android:theme="@style/AppTheme.NoActionBar">
</activity>
1) I launch a notification from a Service with the app closed (killed) using TaskStackBuilder to open MainActivity -> ActivityB in the stack just as documentation says (https://developer.android.com/training/notify-user/navigation) :
Intent resultIntent = new Intent(this, ActivityB.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addNextIntentWithParentStack(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "1")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Title")
.setContentText("Message")
.setAutoCancel(true)
.setContentIntent(resultPendingIntent);
android.app.Notification buildNotification = mBuilder.build();
NotificationManager mNotifyMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotifyMgr.notify(1, buildNotification);
ActivityB在通知点击时被打开,但使用后退按钮并没有转到父活动(MainActivity),而这正是你想用TaskStackBuilder得到的。它让应用程序关闭。
2)当打开了MainActivity的应用处于后台时(主按钮),如果我从另一个应用中分享一个音频文件到该应用,onCreate总是被调用,而不是onNewIntent。看一下launchMode的文档,由于MainActivity是singleTop,并且在堆栈的顶部,它不应该调用onNewIntent吗?
Tested in
Android 10 & Android 11