I've got an application with several activities, for example:
Activity 1 --> Activity 2 --> Activity 3 --> Activity 4
And I would like to close all the activities from any activity and go back at home phone.
You can achieve that by using BroadcastReceivers
:
BaseActivity
like this:public class BaseActivity extends Activity {
private KillReceiver mKillReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mKillReceiver = new KillReceiver();
registerReceiver(mKillReceiver,
IntentFilter.create("kill", "spartan!!!"));
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mKillReceiver);
}
private final class KillReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
finish();
}
}
}
BaseActivity
.Intent intent = new Intent("kill");
intent.setType("spartan!!!");
sendBroadcast(intent);
You can clear all the previous activities using the following flags :
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
I hope it will help you !
Open up AndroidManifest.xml and find the activity that you would like to return to and add the following attribute
android:launchMode="singleTask"
For example, HomeActivity class might have this in android manifest
<activity android:name=".HomeActivity"
android:launchMode="singleTask"/>
At any point, you can close all activities on top of this one by using startActivity the standard way, for example
startActivity(new Intent(this, HomeActivity.class));
If you normally pass extras to the intent, there's no need to do this as it will come back in whatever state it was before, and it's even accompanied by an animation like hitting the back button.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With