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

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


当前回答

/**
 * Check if the service is Running 
 * @param serviceClass the class of the Service
 *
 * @return true if the service is running otherwise false
 */
public boolean checkServiceRunning(Class<?> serviceClass){
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE))
    {
        if (serviceClass.getName().equals(service.service.getClassName()))
        {
            return true;
        }
    }
    return 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服务都会在运行时显示出来,至少在模拟器上是这样。

自Android 8(或Oreo)以来,API getRunningServices已弃用。 当然,你可以使用@SuppressWarnings("deprecation")来消除警告。

如果您的服务不需要有多个实例,那么如何在没有getrunningservices的情况下使用:使用单例模式。

public class MyMusicService extends Service {

    private static MyMusicService instance = null;
    
    public static boolean isMyMusicServiceRunning() {
        return instance != null;
    }

然后你可以调用MyMusicService。ismymusicservicerun从您的活动或其他地方。

你可以使用Android开发者选项中的这个选项来查看你的服务是否仍然在后台运行。

1. Open Settings in your Android device.
2. Find Developer Options.
3. Find Running Services option.
4. Find your app icon.
5. You will then see all the service that belongs to your app running in the background.

在serviceclass内部定义:

 public static Boolean serviceRunning = false;

然后在onStartCommand(…)

 public int onStartCommand(Intent intent, int flags, int startId) {

    serviceRunning = true;
    ...
}

 @Override
public void onDestroy()
{
    serviceRunning = false;

} 

然后,调用if(serviceclass。serviceRunning == true)。