Determining the current foreground application fro

2018-12-31 04:18发布

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 are:

  1. How I should run my application in the background.

  2. How my background application can know what the application currently running in the foreground is.

Responses from folks with experience would be greatly appreciated.

13条回答
低头抚发
2楼-- · 2018-12-31 05:21

Try the following code:

ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> 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.

查看更多
登录 后发表回答