I have an android application i need one function or any broadcast receiver that can check if the app is closed.. i don\'t need to call on destroy in every activity (there i
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (isAppForground(context)) {
// App is in Foreground
} else {
// App is in Background
}
}
private boolean isAppOnForeground(Context context,String appPackageName) {
ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List appProcesses = activityManager.getRunningAppProcesses();
if (appProcesses == null) {
//App is closed
return false;
}
final String packageName = appPackageName;
for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND && appProcess.processName.equals(packageName)) {
// Log.e("app",appPackageName);
return true;
}else{
//App is closed
}
}
return false;
}
}
Add this permission too
try this hope it helps