Implementation method of clearing all activity when exiting Android program

  • 2021-07-01 08:16:21
  • OfStack

This article illustrates the method of clearing all activity when exiting Android program. Share it for your reference, as follows:

In one project, to exit the android program, try restartPackage, killBackgroundProcesses, pass the exception and re-register the Thread. UncaughtExceptionHandler interface + exception mode of Thread in the subclass of Application, and so on, all of which have no effect.

Finally, it is found that as long as the finish method of A is called when jumping from one activity A to another activity B, the program can exit, but the Back operation cannot be realized. Finally, I think of a way: Why don't we control the activity created by the program ourselves? For example, we can put the avtivity created by the program in a global variable, take out each existing activity when exiting the program, and call finish for each activity in turn, and finally the program exits normally.

First, make the following explanations:

(1) We can rewrite an Activity management class, ActivityManager, There is a stack structure inside, Used to store the activity displayed by the user, And exposes several methods, one adds Activity to the stack structure, which is mainly used to add the stack when a new Activity is created, the other takes out an Activity from the stack structure, deletes useless activity from the stack when the user calls the Back key, finally defines a method to empty activity when the system exits, and calls finish method of each Activity to complete the release of memory resources when emptying Activity.

(2) In order to share complex data types, we can rewrite the Application class and define a member in this class-Activity management class ActivityManager, so that it can be shared by all Activity.

(3) When appropriate, we just call the stack-on operation and stack-off operation of ActivityManager. For example, in my requirement, I invoke the stack-on operation at onCreate and the stack-off operation when the user clicks the Back button.

(4) In order to reduce code repeatability, we can customize an Activity base class in actual operation, and rewrite the onCreate () method and onBackPressed method. In onCreate method, we put the current Activity into the custom ActivityManager, and onBackPressed popped the current Activity from ActivityManager.

Look at the main code of ActivityManager class first.


import java.util.Stack;
public class ActivityManager {
  private static Stack<Activity> activityStack;
  private static ActivityManager instance;
  private ActivityManager() {
  }
  public static ActivityManager getScreenManager() {
    if (instance == null) {
      instance = new ActivityManager();
    }
    return instance;
  }
  // Exit the top of the stack Activity
  public void popActivity(Activity activity) {
    if (activity != null) {
      // Extracting the current from the custom collection Activity When, also carried out Activity Close operation of 
      activity.finish();
      activityStack.remove(activity);
      activity = null;
    }
  }
  // Get the current top of the stack Activity
  public Activity currentActivity() {
    Activity activity = null;
    if(!activityStack.empty())
     activity= activityStack.lastElement();
    return activity;
  }
  // Will the current Activity Push into the stack 
  public void pushActivity(Activity activity) {
    if (activityStack == null) {
      activityStack = new Stack<Activity>();
    }
    activityStack.add(activity);
  }
  // Exit all in the stack Activity
  public void popAllActivityExceptOne(Class cls) {
    while (true) {
      Activity activity = currentActivity();
      if (activity == null) {
        break;
      }
      if (activity.getClass().equals(cls)) {
        break;
      }
      popActivity(activity);
    }
  }
}

Take a look at the custom Application class, and the code related to network connection processing can be ignored.


public class ApplicationEx extends Application {
  private static final String TAG = "ApplicationEx";
  private HttpClient httpClient; // Adopt apache Network connection component 
  private ActivityManager activityManager = null;
  public ApplicationEx() {
  }
  public ActivityManager getActivityManager() {
    return activityManager;
  }
  public void setActivityManager(ActivityManager activityManager) {
    this.activityManager = activityManager;
  }
  @Override
  public void onCreate() {
    super.onCreate();
    httpClient = createHttpClient();
   // Initialize customization Activity Manager 
    activityManager = ActivityManager.getScreenManager();
  }
  @Override
  public void onLowMemory() {
    super.onLowMemory();
    shutdownHttpClient();
  }
  @Override
  public void onTerminate() {
    super.onTerminate();
    shutdownHttpClient();
  }
  private void shutdownHttpClient() {
    if (httpClient != null && httpClient.getConnectionManager() != null) {
      httpClient.getConnectionManager().shutdown();
    }
  }
  private HttpClient createHttpClient() {
    Log.d(TAG, "createHttpClient()...");
    HttpParams params = new BasicHttpParams();
    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
    HttpProtocolParams.setUseExpectContinue(params, true);
    SchemeRegistry schReg = new SchemeRegistry();
    schReg.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schReg.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));
    // Solve the security problem of multithreaded access 
    ClientConnectionManager connectionManager = new ThreadSafeClientConnManager(params, schReg);
    return new DefaultHttpClient(connectionManager, params);
  }
  public HttpClient getHttpClient() {
    if (httpClient != null) {
      return httpClient;
    } else {
      return createHttpClient();
    }
  }
}

Let's look at one of our custom Acitivity base classes.


public abstract class AbstractTemplateActivity extends Activity {
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ApplicationEx application = (ApplicationEx) this.getApplication();
    application.getActivityManager().pushActivity(this);
  }
  @Override
  public void onBackPressed() {
    super.onBackPressed();
    ApplicationEx application = (ApplicationEx) getApplication();
    application.getActivityManager().popActivity(this);
  }
}

In this way, only our Activity inherits AbstractTemplateActivity, so we don't need to write ApplicationEx application = (ApplicationEx) this. getApplication () in every Activity; application. getActivityManager (). pushActivity (this); Wait for the relevant code.

The complete exit of Activity can be achieved in android versions above 2.1.

For more readers interested in Android related content, please check the topics of this site: "Summary of Android Communication Mode", "Summary of Android Debugging Skills and Common Problem Solutions", "Introduction and Advanced Tutorial of Android Development", "Summary of Android Multimedia Operation Skills (Audio, Video, Recording, etc.)", "Summary of Android Basic Component Usage", "Summary of Android View View Skill", "Summary of Android Layout layout Skill" and "Summary of Android Control Usage"

I hope this article is helpful to everyone's Android programming.


Related articles: