检查服务是否正在运行,表现不正常

时间:2016-04-01 06:46:11

标签: android

我创建了一个布尔值来检查服务是否正在运行,如果它正在运行我希望它显示linearlayoutA,如果它没有运行,我希望它显示另一个linearlayoutB。

问题在于,当我启动活动时,它显示正确的线性布局,如果服务正在运行,则显示linearlayoutA如果未运行它会显示linearlayoutB但是当我在活动中启动服务时它显示为linearlayoutB而不是即使服务停止直到我关闭应用程序并打开它,也会更改为A.检查方法

public boolean isRunning(Class<? extends Service> serviceClass) {
        final Intent intent = new Intent(TimerActivity.this, serviceClass);
        return (PendingIntent.getService(TimerActivity.this, CODE, intent, PendingIntent.FLAG_NO_CREATE) != null);
    }

这是我在活动的onCreate中调用它的方式

if(isRunning(TimerLocationService.class)){
            setWaitScreen(true);
        }else{
            setWaitScreen(false);
        }

1 个答案:

答案 0 :(得分:0)

试试这个。

private Boolean isServiceRunning(String serviceName) {
    ActivityManager activityManager = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo runningServiceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceName.equals(runningServiceInfo.service.getClassName())) {
            return true;
        }
    }
    return false;
}

我希望这对你有所帮助。

相关问题