Search code examples
androidactivity-finishandroid-application-class

MyApplication.java did not run at the second time app started?


I have 1 application custom class MyApplication.java and 1 activity MainActivity.java.

At the first time when I start app, class MyApplication.java run correctly. Then I exit app by finish the activity

MainActivity.this.finish();

Then I click the app icon in screen to start it again. But this time, MyApplication.java do not run. It means that I can't exit app by finishing all activities?

I can't explain why.

P/s: Here is my code

MyApplication.java

@Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate: ");
    }

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Log.d(TAG, "onCreate: ");
}

@Override
public void onBackPressed() {
    this.finish();
}

Solution

  • In the Application class, the onCreate() method is called only if the process was ended when you exited the application. Usually the process is stopped when the system needs memory or if you exit the app using the back button instead of the home button. However, you cannot rely on it being terminated.

    If you really want to kill your process when exiting the application, you can call System.exit(0); when the user presses the back key on your first activity.

    @Override
    public void onBackPressed() {
        MainActivity.this.finish();          
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
        getParent().finish();
    }
    

    Note: This is definitely not recommended since it means fighting against the way the Android OS works and might cause problems.