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

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


当前回答

自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从您的活动或其他地方。

其他回答

检测服务是否正在运行的唯一有效/最快/干净的方法是创建PING/PONG功能。

在服务内部实现Messenger或AIDL方法:isAlive()——它返回服务的状态。

不要实现广播,因为它们可能被错过。

我只是想给@Snicolas的答案加上一个注释。以下步骤可以使用/不调用onDestroy()来检查停止服务。

onDestroy() called: Go to Settings -> Application -> Running Services ->选择并停止服务。 onDestroy()未调用:转到设置->应用程序->管理应用程序->选择并“强制停止”您的应用程序,其中您的服务正在运行。但是,由于您的应用程序在这里停止,因此服务实例也肯定会停止。

最后,我想提一下,在单例类中使用静态变量的方法对我来说是有效的。

摘自Android文档:

比如sendBroadcast(Intent),但是如果有任何接收器 这个函数将阻塞并立即分发它们 返回之前。

你可以把这次入侵看成是"ping "服务。因为我们可以同步广播,所以我们可以在UI线程上同步广播并获得结果。

服务

@Override
public void onCreate() {
   LocalBroadcastManager
     .getInstance(this)
     .registerReceiver(new ServiceEchoReceiver(), new IntentFilter("ping"));
     //do not forget to deregister the receiver when the service is destroyed to avoid
     //any potential memory leaks 
}

private class ServiceEchoReceiver extends BroadcastReceiver {
    public void onReceive (Context context, Intent intent) {
      LocalBroadcastManager
         .getInstance(this)
         .sendBroadcastSync(new Intent("pong"));
    }
}

活动

    bool serviceRunning = false;

    protected void onCreate (Bundle savedInstanceState){
        LocalBroadcastManager.getInstance(this).registerReceiver(pong, new IntentFilter("pong"));
        LocalBroadcastManager.getInstance(this).sendBroadcastSync(new Intent("ping"));
        if(!serviceRunning){
           //run the service
        }
    }

    private BroadcastReceiver pong = new BroadcastReceiver(){
        public void onReceive (Context context, Intent intent) {
          serviceRunning = true;   
        }
    }

当然,在许多应用程序中,赢家是服务上的静态布尔字段,在service . oncreate()中设置为true,在service . ondestroy()中设置为false,因为它要简单得多。

在kotlin中,你可以在伴侣对象中添加布尔变量,并从任何你想要的类中检查它的值:

companion object{
     var isRuning = false

}

在创建和销毁服务时更改它的值

 override fun onCreate() {
        super.onCreate()
        isRuning = true
    }

override fun onDestroy() {
    super.onDestroy()
    isRuning = false
    }

你可以使用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.