How to land or navigate to previous activity if click on back button

315 views Asked by At

In My application i have implemented Notification. My Problem is if I click on received Notification it will redirect to the Activity which I have given there if I click on inbuilt Back button It will closing the application and going out. What I need is if I click on Back button, it should land to previous Activity how to set that. Ex: If we got Facebook notifications if we click on that it will redirect to comment are like page, there if we click on back button it will redirect to Facebook main form.

3

There are 3 answers

0
Khushal Chouhan On BEST ANSWER

You need to override onBackPressed method:

@override
public void onBackPressed();
{
 super.onBackPressed()
 Intent i = new Intent(this, PreviousActivity.class);
 i.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
 startActivity(i);
}

If you are using eclipse, then right click on editor>>source>>override/implement method.

0
Raman On

call function onBackPressed()

public void onClick() {
    onBackPressed();
}
0
Ionut Negru On

You can make use of the parent activity which will be set in your manifest like this:

<activity
    android:name=".YourActivity"
    android:parentActivityName=".YourParentActivity">

    <!-- Parent activity meta-data to support 4.0 and lower -->
    <meta-data
            android:name="android.support.PARENT_ACTIVITY"
            android:value=".YourParentActivity"/>
</activity>

After this in your code, override the onBackPressed() method and do this:

NavUtils.navigateUpFromSameTask(this);

This method to navigate should be used only if your app is the owner of the current task, otherwise this method should be used:

Intent upIntent = NavUtils.getParentActivityIntent(this);
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
    // This activity is NOT part of this app's task, so create a new task
    // when navigating up, with a synthesized back stack.
    TaskStackBuilder.create(this)
            // Add all of this activity's parents to the back stack
            .addNextIntentWithParentStack(upIntent)
            // Navigate up to the closest parent
            .startActivities();
} else {
    // This activity is part of this app's task, so simply
    // navigate up to the logical parent activity.
    NavUtils.navigateUpTo(this, upIntent);
}