I have a class (Not an Activity) that has a stack of activities in background. Some times, I want to close an old activity from that stack, but most of the times the activities are so in background that if I use finish()
, it doesn't work.
So, I was thinking on using putExtra
to send the message to that activity so it can close on the onResume()
.
I'm trying to do it this way without success:
On my NoActivity.class:
public void removeActivityFromStack(Activity activity){
for(int i = mActivityStack.size(); i>0; i--){
if(mActivityStack.get(i - 1).equals(activity)){
mActivityStack.remove(i-1);
activity.getIntent().putExtra(CLOSE_ACTIVITY, true);
}
}
}
And on the MyActivity
.class:
@Override
protected void onResume() {
super.onResume();
Bundle bundle = getIntent().getExtras();
if(bundle != null && bundle.getBoolean(getString(R.string.bundle_cerrar_activity), false)){
this.finish();
}
}
Any help will be appreciated.
I also tried using BroadcastReceiver
to close those activities, but it still doesn't work. I tried the next way:
On my NoActivity.class
public void removeActivityFromStack(Activity activity){
for(int i = mActivityStack.size(); i>0; i--){
if(mActivityStack.get(i - 1).equals(activity)){
IntentFilter filter = new IntentFilter();
CloseActivitiesBroadcastReceiver baseActivityReceiver = new CloseActivitiesBroadcastReceiver();
filter.addAction(CLOSE_ACTIVITY);
current.registerReceiver(baseActivityReceiver, filter);
current.sendBroadcast(new Intent(CLOSE_ACTIVITY));
mActivityStack.remove(i-1);
}
}
}
And on CloseActivitiesBroadcastReceiver.java:
public class CloseActivitiesBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(context.getString(R.string.bundle_cerrar_activity))) {
((Activity)context).finish();
}
}
}
Okay, this is a Little dirty answer, but is the only one that I could make work. If somebody gets a better answer, post it.
On my NoActivity.class:
public void removeActivityFromStack(Activity activity){
for(int i = 0; i<mActivityStack.size(); i++){
if(mActivityStack.get(i).equals(activity)){
activity.finish()
mActivityStack.remove(i);
}
}
}
This way, if the activity is in foreground, will close on finish()
. Else, it won't close at all. But for this case:
On the MyActivity.class:
@Override
protected void onResume() {
super.onResume();
if(!mNoActivityInstance.getActivityStack().contains(this)){
finish();
}
}
In my case, NoActivity.class works as a Singleton