I have 3 activities. Activity A which leads to activity B, which in turn can go back to activity A or start activity C. However, if I press back in activity C the app should
You can just override the back key behavior:
Activity A starts activity B
Pressing Back on activity B should lead to A
Activity B starts activity C
Pressing Back on activity C should close the app
Note that I don't call super from onBackPressed. This also allows you to override the browse stack mechanism for Android, which I find to be a big advantage, since currently there doesn't seem to be a way to clear the single oldest item from the browse stack in a simple way.
public class B extends Activity
{
...
@Override
public void onBackPressed()
{
// Start activity A
Intent aIntent = new Intent(this, A);
startActivity(bIntent);
}
...
}
public class C extends Activity
{
...
@Override
public void onBackPressed()
{
// Close
finish();
}
...
}
You can specifically finish the parent activity if needed too, but using this method, you don't have to worry about it.
Create instance of ActivityB.
on ActivityB.java
public static ActivityB instanceOfActivityB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instanceOfActivityB = this;
}
on ActivityC.java
void onClose() {
ActivityB.instanceOfActivityB.finish();
finish();
}
Hope it helps!
The following code should do it for you. Almost in all other approaches your app will remain in recent apps. Javadoc can be found at, https://developer.android.com/reference/android/app/ActivityManager.AppTask.html#finishAndRemoveTask()
ActivityManager am = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
if(am != null) {
List<ActivityManager.AppTask> tasks = am.getAppTasks();
if (tasks != null) {
tasks.get(0).finishAndRemoveTask();
}
}
if you are on Activity A and started another activity called Activity B. Activity A --> Activity B
And now want to close both activities.
then use the below code in Activity B.
B.this.finish();
And use this code in Activity A:
startActivity(new Intent(A.this, B.class));
finish();
As soon as activity B will finish, Activity A will also finish.
There is one drawback, I do not know may be you want this or not.
Drawback is that If user is on Activity B and s/he press back button to move on the Activity A. Then, Activity A will also finish in this case.
This is working perfectly:
btn_back.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v) {
Player.this.finish();
}
});
None of that worked for me. So I found out a solution. The help clearly lists that Intent.FLAG_ACTIVITY_CLEAR_TASK must be used with Intent.FLAG_ACTIVITY_NEW_TASK. So here is a code that worked for me.
Intent intent=new Intent(ActivityB.this, ActivityC.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);