Now I have my Own Blog. Follow Link to learn more about Android Development.
In this example I will explain how to check if your Android Application is running in foreground or it is in background.
Note: we do not need to add any permission for this code. we will be using ActivityManager class
and its method getRunningAppProcesses()
getRunningAppProcesses() Returns a list of application processes that are running on the device.
Also I am using AsyncTask because we should not call ActivityManager.getRunningAppProcesses()
from UI thread it will return importance
IMPORTANCE_FOREGROUND
for your task no matter whether it is actually in the foreground or not. private class CheckIfForeground extends AsyncTask<Void, Void, Void> {
@Override
protected Void doInBackground(Void... voids) {
ActivityManager activityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
Log.i("Foreground App", appProcess.processName);
if (mContext.getPackageName().equalsIgnoreCase(appProcess.processName)) {
Log.i(Constants.TAG, "foreground true:" + appProcess.processName);
foreground = true;
// close_app();
}
}
}
Log.d(Constants.TAG, "foreground value:" + foreground);
if (foreground) {
foreground = false;
close_app();
Log.i(Constants.TAG, "Close App and start Login Activity:");
} else {
//if not foreground
close_app();
foreground = false;
Log.i(Constants.TAG, "Close App");
}
return null;
}
}
and execute AsyncTask like this.
new CheckIfForeground().execute();
Please Note this code is tested on Android Version 5.0.2
Author:
Hammad Tariq
Android Developer