By using onPause(), I can check if an activity is going to background or not. My problem is this onPause() is call each time even if I am going to another activity from this activity.
So my main problem is ,if I am minimizing the app by pressing home button I want to remove app from task manager and this code is write in each activity when app is going to background BUT not using onPause().
My code snippet is below ->
@Override
public void onPause() {
if (isBackgroundRunning(this)){
ExitActivity.exitApplication(getApplicationContext());
}
super.onPause();
}
public static boolean isBackgroundRunning(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
for (String activeProcess : processInfo.pkgList) {
if (activeProcess.equals(context.getPackageName())) {
//If your app is the process in foreground, then it's not in running in background
return true;
}
}
}
}
return true;
}
ExitActivity is used for remove the app from task manager.
public class ExitActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
finish();
}
public static void exitApplication(Context context) {
Intent intent = new Intent(context, ExitActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
context.startActivity(intent);
}
}
I saw most of the questions related to this but can't find out the solution. Please help me. Thanks in advance :)
Try calling finish() in your onPause() method in your apps parent/launcher activity. That should kill the app when the user presses the home button