Wai Yan Hein Wai Yan Hein - 6 months ago 31
Android Question

Opening activity from notification has issue with Activity Life Cycle in Android

I am developing an Android app. In my app, I am opening the Activity when a notification is clicked. Please see my scenario below.

I have two activity - MainActivity and SecondActivity

Main Activity can open SecondActivity

OnBackPressed on SecondActivity, MainActivity will be displayed back it is the activity that opens SecondActivity. OnBackPressed of MainActivity, application will exit. It is the default activity application launches first. Now I am having a problem because I am openning SecondActivity from inside of a service.

This is how I open SecondActivity from service

private void showTrollPostNotification(String message)
notification = new NotificationCompat.Builder(getApplicationContext());

Intent i = new Intent(getApplicationContext(), SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(),0,i,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager nm = (NotificationManager)getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);

The problem is that when I open from service and OnBackPressed of SecondActivity, application exits. What I want to do is I always want to open MainActivity, when I press back button inside SecondActivity. So what I tried is
override the onBackPressed of SecondActivity. I start MainActivity in the onBackPressed. But the problem is when I open SecondActivity from notification, then press back button, it opens the MainActivity. But when I press back button then, it opens SecondActivity back. So please what can I do to get MainActivity always opened in OnBackPressed of SecondActivity without having the issue with Activity Cycle like happening now. Please help me. How can I achieve it?

This is Additional

This is SecondActivity in Manifest

android:label="Post Details"
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />

This is onBackPressed of SecondActivity

public void onBackPressed() {
Intent intent = new Intent(getApplicationContext(),MainActivity.class);


What happens is that the SecondActivity gets on the history backstack. So in your case the SecondActivity does not need to be on the backstack. To achieve this you can flag noHistory="true" in your Manifest.xml

  android:noHistory="true" />

Edit: Normally you don't need to do this since noHistory="true" does it, but you can try to call finish().

public void onBackPressed() {
    Intent intent = new Intent(this,MainActivity.class);