We often encounter the situation that an activity needs to jump back to another activity or destroy it directly. In this case, how can we design a better mechanism to deal with this problem? Here I summarize two solutions.
1. Use activitymanager to save the activity on the skipped path to activitymanager, and delete it through activitymanager when necessary.
But there is a problem with this method. If activity is referenced, it will cause memory leak. Although the function of this module is used up and all the activities in it can be destroyed, it will cause memory leakage during operation.
public class ScreenManager { private static Stack<Activity> activityStack; private static ScreenManager instance; private ScreenManager(){} public static ScreenManager getScreenManager(){ if(instance==null){ instance=new ScreenManager(); } return instance; } public void popActivity(){ if(activityStack.empty()) return; Activity activity = activityStack.lastElement(); if(activity!=null){ activity.finish(); activity=null; } } public void popActivity(Activity activity){ if(activity!=null){ activity.finish(); if(!activityStack.empty()){ activityStack.remove(activity); activity=null; } } } public Activity currentActivity(){ if(!activityStack.empty()){ Activity activity=activityStack.lastElement(); return activity; }else{ return null; } } public void pushActivity(Activity activity){ if(activityStack==null){ activityStack=new Stack<Activity>(); } activityStack.add(activity); } public void popAllActivityExceptOne(Class cls){ while(true){ Activity activity=currentActivity(); if(activity==null){ break; } if(activity.getClass().equals(cls) ){ break; } popActivity(activity); } } public void popAllActivity(){ while(true){ Activity activity=currentActivity(); if(activity==null){ break; } activity.finish(); popActivity(activity); } } public boolean isEmpty(){ if(activityStack==null){ activityStack=new Stack<Activity>(); } return activityStack.empty(); } }
2. The second method is provided by activity
CustomerActivity.this.startActivityForResult(intent,REQUESTCODE);
as well as
@Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUESTCODE) { if (data != null && data.getBooleanExtra(REQUESTFINISH, false)) { finish(); } } }
This system has its own methods for processing.
Specifically, when all activities on the startup path pass the parameters in the past, and when the node is destroyed, call
Intent intent = new Intent(); intent.putExtra(IS_CONFIRM, isConfirm); CustomerActivity.this.setResult(RESULT_CODE, intent);
By calling this method, the system will take the destruction information back to the node and destroy the node activity on the path.
Of course, there may be a better solution. Please leave a message below