Determining the current foreground application from a background task or service

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

    With regards to "2. How my background application can know what the application currently running in the foreground is."

    Do NOT use the getRunningAppProcesses() method as this returns all sorts of system rubbish from my experience and you'll get multiple results which have RunningAppProcessInfo.IMPORTANCE_FOREGROUND. Use getRunningTasks() instead

    This is the code I use in my service to identify the current foreground application, its really easy:

    ActivityManager am = (ActivityManager) AppService.this.getSystemService(ACTIVITY_SERVICE);
    // The first in the list of RunningTasks is always the foreground task.
    RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0);
    

    Thats it, then you can easily access details of the foreground app/activity:

    String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
    PackageManager pm = AppService.this.getPackageManager();
    PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
    String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();
    

    This requires an additional permission in activity menifest and works perfectly.

    
    

提交回复
热议问题