App exit detection is difficult, but to get the app "to exit" the state is much easier, quit the moment is not really quit, Activitymanager to destroy activity, also need some time and resources.
The result of the operation is as follows:
GIF makes a rough comparison,
Two activity interface is not introduced, mainly when the app launches a service, the application code is as follows:
Public class MyApplication extends Application { @Override publicvoid onCreate () { Super.oncreate (); Intent Intent=new Intent (This, checkexitservice. Class); Getapplicationcontext (). StartService (intent); }}
The service code is as follows:
Public classCheckexitservice extends Service {PrivateString PackageName ="Test.minwenping.com.appexitdemo"; @Nullable @Override Publicibinder onbind (Intent Intent) {return NULL; } @Override Public voidontaskremoved (Intent rootintent) {super.ontaskremoved (rootintent); Toast.maketext (Checkexitservice. This,"The app is going to quit.", Toast.length_short). Show (); } //callback for service exception stop@Override Public intOnstartcommand (Intent Intent,intFlagsintStartid) {Activitymanager Activtymanager=(Activitymanager) Getsystemservice (Activity_service); List<ActivityManager.RunningAppProcessInfo> runningappprocesses =activtymanager.getrunningappprocesses (); for(inti =0; I < runningappprocesses.size (); i++) { if(Packagename.equals (runningappprocesses.Get(i). ProcessName)) {Toast.maketext ( This,"The app is still running", Toast.length_long). Show (); } } returnStart_not_sticky; } @Override Public voidonCreate () {super.oncreate (); Toast.maketext (Checkexitservice. This,"The app detection service opens", Toast.length_short). Show (); }}
and try the daemon thread, the UI has only one thread and wants to do it, but it all fails.
Android app Exit detection