Android checking whether the app is closed

后端 未结 6 1540
孤独总比滥情好
孤独总比滥情好 2020-12-03 12:52

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

6条回答
  •  暖寄归人
    2020-12-03 13:49

    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

提交回复
热议问题