我想从我的服务类中找到在前台运行的应用程序。我曾经 RunningAppProcessInfo.IMPORTANCE_FOREGROUND
检测过它。但是会出现以下问题:
- 它在前台提供了许多应用程序状态。
- 如果我打开任何应用程序,则它不会显示其包名称。
代码:
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;
}
}