Determining the current foreground application from a background task or service

后端 未结 13 1433
我寻月下人不归
我寻月下人不归 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 02:57

    Try the following code:

    ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
    List appProcesses = activityManager.getRunningAppProcesses();
    for(RunningAppProcessInfo appProcess : appProcesses){
        if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
            Log.i("Foreground App", appProcess.processName);
        }
    }
    

    Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.

    I hope this answers your question.

提交回复
热议问题