Determining the current foreground application from a background task or service

后端 未结 13 1452
我寻月下人不归
我寻月下人不归 2020-11-22 02:29

I wish to have one application that runs in the background, which knows when any of the built-in applications (messaging, contacts, etc) is running.

So my questions

相关标签:
13条回答
  • 2020-11-22 03:11

    This is how I am checking if my app is in foreground. Note I am using AsyncTask as suggested by official Android documentation.`

    `

        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 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();

    0 讨论(0)
提交回复
热议问题