Intent - if activity is running, bring it to front, else start a new one (from notification)

前端 未结 8 1233
星月不相逢
星月不相逢 2020-11-27 13:57

My app has notifications, which - obviously - without any flags, start a new activity every time so I get multiple same activities running on top of each other, which is jus

8条回答
  •  情深已故
    2020-11-27 14:32

    This is old thread, but for all those who is still seeking for answer, here is my solution. It is purely in code, without manifest settings:

    private static PendingIntent prepareIntent(Context context) {
      Intent intent = new Intent(context, MainActivity.class);
      intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);      
      return PendingIntent.getActivity(context, NON_ZERO_REQUEST_CODE, intent, 
        PendingIntent.FLAG_UPDATE_CURRENT);
    }
    

    Here FLAG_ACTIVITY_SINGLE_TOP opens existing activity if it is at the top of task stack. If it is not at the top, but inside stack, FLAG_ACTIVITY_CLEAR_TOP will remove all activities on top of target activity and show it. If activity is not in the task stack, new one will be created. A crucially important point to mention - second parameter of PendingIntent.getActivity(), i.e. requestCode should have non-zero value (I even called it NON_ZERO_REQUEST_CODE in my snippet), otherwise those intent flags will not work. I have no idea why it is as it is. Flag FLAG_ACTIVITY_SINGLE_TOP is interchangeable with android:launchMode="singleTop" in activity tag in manifest.

提交回复
热议问题