从服务中找到在前台运行的应用程序 [英] find application running in foreground from service

查看:78
本文介绍了从服务中找到在前台运行的应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的Service类中找到在前台运行的应用程序.我曾使用 RunningAppProcessInfo.IMPORTANCE_FOREGROUND 进行检测.但是出现了以下问题:

I want to find application running in foreground from my Service class. I had used RunningAppProcessInfo.IMPORTANCE_FOREGROUND to detect it. But following problems arises:

  1. 它在前台提供了许多应用程序状态.
  2. 如果我打开任何应用程序,则不会显示其程序包名称.

代码:

 public class TapCountService extends Service{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    List<RunningAppProcessInfo> procInfos=getRunningAps();
    int loop=0;
    for (RunningAppProcessInfo runningAppProcessInfo : procInfos) {
        Toast.makeText(TapCountService.this, procInfos.get(loop).processName, Toast.LENGTH_SHORT).show();
        System.out.println("Process Name=====>"+procInfos.get(loop).processName);
        if(procInfos.get(loop).importance== RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
            Toast.makeText(TapCountService.this, procInfos.get(loop).processName, Toast.LENGTH_SHORT).show();
        } 
        ++loop;
    }
    return super.onStartCommand(intent, flags, startId);
}

/**
 * This method returns list of running application.
 * @return List<RunningAppProcessInfo>: containing application informations.
 */
private List<RunningAppProcessInfo> getRunningAps(){
    ActivityManager actvityManager = (ActivityManager)this.getSystemService( ACTIVITY_SERVICE );
    List<RunningAppProcessInfo> procInfos = actvityManager.getRunningAppProcesses();
    return procInfos;
}

}

推荐答案

以下是获取当前最先进的地面应用程序的步骤.

Following is the steps for getting currently fore ground app.

1 getForegroundApp - returns the foreground application.
2 getActivityForApp - returns the activity of the found app.
3 isStillActive - determines if a earlier found app is still the active app.
4 isRunningService - a helper function for getForegroundApp

以下是代码

   // Add permission 
   <uses-permission android:name="android.permission.GET_TASKS"/>

    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);
   String foregroundTaskPackageName = foregroundTaskInfo .topActivity.getPackageName();
   PackageManager pm = AppService.this.getPackageManager();
   PackageInfo foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0);
   String foregroundTaskAppName = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString();

这篇关于从服务中找到在前台运行的应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆