Finish Activity From Another Activity
Solution 1:
In your onCreate()
method assign a static instance to a variable to create a Singleton:
publicstaticActivityA instance = null;
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
instance = this;
}
@Overridepublicvoidfinish() {
super.finish();
instance = null;
}
then in C:
publicvoidonCreate(Bundle savedInstanceState) {
if(ActivityA.instance != null) {
try {
ActivityA.instance.finish();
} catch (Exception e) {}
}
}
(Repeat above code for B as well as A)
I would say this is NOT elegant and is bound to introduce strange lifecycle bugs.
It would be better if you could tweak your requirement - if you can't you could perhaps use a single Activity and change A, B and C into Fragments
?
I would have suggested a Broadcast but as I understand it you can't have instance level broadcast receivers on "non resumed" Activities.
Using a Service
to bind to the Activities seems like overkill - but you might want to consider that if the above doesn't work.
Good luck!
Solution 2:
((Activity)context_of_another_activity).finish();
Solution 3:
I realize this is a very late response, but I feel the BroadcastReceiver
is the best approach to this question.
In Activity A add this
//class objectBroadcastReceiver receiver;
//add this to onCreate()
receiver =newBroadcastReceiver() {
@OverridepublicvoidonReceive(Context context, Intent intent) {
finish();
}
};
IntentFilter filter =newIntentFilter();
filter.addAction("FINISH_A");
registerReceiver(receiver, filter);
//add this to Activity A as wellprotectedvoidonDestroy() {
super.onDestroy();
unregisterReceiver(receiver);
}
Then, in Activity C onCreate() (or when ever you want to finish Activity A)
Intent local =new Intent();
local.setAction("FINISH_A");
sendBroadcast(local);
Solution 4:
When you start C from B, do it in this way:
Intent intent = newIntent(this, A.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
Now, C starts, but A and B are gone.
However, I think it is better if you can rethink your design such that C does not depend on A being finished or not.
Post a Comment for "Finish Activity From Another Activity"