【问题标题】:Check if service is available检查服务是否可用
【发布时间】:2016-06-03 09:51:54
【问题描述】:

在调用Context.bindService 之前,我需要知道特定服务是否可用(正在运行或可以创建)。

有没有办法检查?

【问题讨论】:

    标签: android service bindservice


    【解决方案1】:

    您可以使用代码检查服务是否正在运行

    private boolean isMyServiceRunning(Class<?> serviceClass) {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
            if (serviceClass.getName().equals(service.service.getClassName())) {
                return true;
            }
        }
        return false;
    }
    

    我称之为:

    isMyServiceRunning(MyService.class)
    

    hack bods 对此Google Group Discussion 的回复的一些摘录

    如果您的客户端和服务器代码是同一个 .apk 的一部分,并且您使用具体的 Intent(指定确切服务类的意图)绑定到服务,那么您可以简单地让您的服务设置一个全局变量正在运行,您的客户可以检查。

    我们故意没有 API 来检查服务是否正在运行,因为几乎没有失败,当您想要执行类似的操作时,您的代码中会出现竞争条件。

    【讨论】:

      【解决方案2】:

      请看cmets

       ServiceConnection serviceConnection = new ServiceConnection() {
              @Override
              public void onServiceConnected(ComponentName name, IBinder service)    {
          // capture the service object , check for alive or not
               service.isBinderAlive(); 
      
              }
      
              @Override
              public void onServiceDisconnected(ComponentName name) {
      
              }
          };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多