如何查看后台服务是否正在运行?

我想要一个切换服务状态的Android活动——它让我打开它,如果它是关闭的,如果它是关闭的。


当前回答

我稍微修改了上面给出的一个解决方案,但是传递的是类而不是泛型字符串名称,以便确保比较来自同一个方法class. getname()的字符串

public class ServiceTools {
    private static String LOG_TAG = ServiceTools.class.getName();

    public static boolean isServiceRunning(Context context,Class<?> serviceClass){
        final ActivityManager activityManager = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
        final List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE);

        for (RunningServiceInfo runningServiceInfo : services) {
            Log.d(Constants.TAG, String.format("Service:%s", runningServiceInfo.service.getClassName()));
            if (runningServiceInfo.service.getClassName().equals(serviceClass.getName())){
                return true;
            }
        }
        return false;
    }
}

然后

Boolean isServiceRunning = ServiceTools.isServiceRunning(
                    MainActivity.this.getApplicationContext(),
                    BackgroundIntentService.class);

其他回答

对于这里给出的用例,我们可以简单地使用stopService()方法的返回值。如果存在指定的服务并且该服务被终止,则返回true。否则返回false。因此,如果结果为false,您可以重新启动服务,否则可以确保当前服务已停止。(收集如果你看一下这个就更好了。

在Kotlin课上,geekQ的反应。由于geekQ

fun isMyServiceRunning(serviceClass : Class<*> ) : Boolean{
    var manager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
    for (service in manager.getRunningServices(Integer.MAX_VALUE)) {
        if (serviceClass.name.equals(service.service.className)) {
            return true
        }
    }
    return false
}

调用

isMyServiceRunning(NewService::class.java)

这更适用于Intent Service调试,因为它们会生成一个线程,但也适用于常规服务。我找到这个线程感谢宾

在我的例子中,我摆弄了调试器并找到了线程视图。它看起来有点像微软Word里的项目符号图标。无论如何,您不必在调试器模式下使用它。单击该流程并单击该按钮。任何Intent服务都会在运行时显示出来,至少在模拟器上是这样。

放轻松,伙计们……:)

我认为最合适的解决方案是在SharedPreferences中保存一个关于服务是否正在运行的键-值对。

逻辑是很直接的;在你的服务等级的任何理想职位;输入一个布尔值,作为服务是否正在运行的标志。然后在应用程序中任意位置读取这个值。

我在我的应用程序中使用的示例代码如下:

在我的服务类(音频流服务),我执行以下代码时,服务是起;

private void updatePlayerStatus(boolean isRadioPlaying)
{
        SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.str_shared_file_name), Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putBoolean(getString(R.string.str_shared_file_radio_status_key), isRadioPlaying);
        editor.commit();
}

然后在我的应用程序的任何活动中,我在以下代码的帮助下检查服务的状态;

private boolean isRadioRunning() {
        SharedPreferences sharedPref = this.getSharedPreferences(getString(R.string.str_shared_file_name), Context.MODE_PRIVATE);

        return sharedPref.getBoolean(getString(R.string.str_shared_file_radio_status_key), false);
}

没有特殊权限,没有循环……简单的方法,干净的解决方案:)

如果您需要更多的信息,请参考链接

希望这能有所帮助。

onDestroy并不总是在服务中调用,所以这是无用的!

例如:只需要对Eclipse做一点更改就可以再次运行应用程序。使用SIG: 9强制退出应用程序。