-2

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();
}
Qk Lahpita
  • 427
  • 2
  • 10
  • 18

2 Answers2

0

it's because this line MainActivity.this.finish();

will only close the activity but the application is still running as you don't have the privilege to close the app completely and as a prove of that after you click the button which runs MainActivity.this.finish(); try to see the background apps on your device you will see your app Finally the application class runs once the app starts and get along till the app is closed from the device apps stack manually.

mhemdan
  • 101
  • 2
  • 9
  • How I can close application? I have used android.os.Process.killProcess(android.os.Process.myPid()) after MainActivity.this.finish(), but the app restart as soon as I press back button! – Qk Lahpita Apr 10 '17 at 08:50
  • It's not something you could do unfortunately according to my search but if you could make sure you have only single process for this app your solution will work though the only one who is capable of setting resources and processes to application is the system itself and differentiate from one to another – mhemdan Apr 10 '17 at 09:51
0

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.

Priyank Patel
  • 12,244
  • 8
  • 65
  • 85