我有一个可以在前台运行的服务,如何检查我的实现是否正常工作?

最佳答案

private boolean isServiceRunning(String serviceName){
    boolean serviceRunning = false;
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> l = am.getRunningServices(50);
    Iterator<ActivityManager.RunningServiceInfo> i = l.iterator();
    while (i.hasNext()) {
        ActivityManager.RunningServiceInfo runningServiceInfo = i
                .next();

        if(runningServiceInfo.service.getClassName().equals(serviceName)){
            serviceRunning = true;

            if(runningServiceInfo.foreground)
            {
                //service run in foreground
            }
        }
    }
    return serviceRunning;
}

如果您想知道您的服务是否正在前台运行,请打开其他胖应用程序,然后检查服务是否仍在运行,或者仅检查标志service.foreground

08-16 05:36