【问题标题】:Stop a service that was started from another service, in another activity?在另一个活动中停止从另一个服务启动的服务?
【发布时间】:2015-11-02 22:43:00
【问题描述】:

我有一个粘性服务 B,它是从服务 A 启动的。服务 A 在启动服务 B 后很快自行完成。我想从 Activity C 停止服务 B。我该怎么做?

This 链接提供了一种从另一个活动停止服务的方法,但在这种情况下,服务是由一个活动启动的。

【问题讨论】:

    标签: android android-intent android-activity android-service android-service-binding


    【解决方案1】:

    您可以考虑使用 BroadcastReceiver 将事件传递给服务并让它自行终止。

    【讨论】:

    • 您可以从任何您想要的地方广播事件并在任何您想要的地方捕捉它。我建议在您的服务中创建一个广播接收器。或者为此使用任何其他事件总线系统。
    • 我尝试按照您的建议进行操作,但服务没有停止。
    【解决方案2】:

    您需要从您的活动中调用stopService。只要您在意图中提供有效的上下文,Service 是由 Activity 还是由另一个 Service 启动的都没有关系。如果服务未绑定到任何客户端,则调用stopService 将停止服务。

    stopService(new Intent(ActivityC.this, ServiceB.class));
    

    如果您希望服务自行停止,请在服务内调用stopSelf()

    【讨论】:

      【解决方案3】:

      http://developer.android.com/reference/android/app/Service.html#onStartCommand(android.content.Intent, int, int)

      1.创建函数handleStart()

      private void handleStart(){
          //write your code here
      }
      


      2.覆盖onStartCommand

      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
          // TODO Auto-generated method stub
      
          if(startId == Service.START_STICKY) {
              handleStart();
              return super.onStartCommand(intent, flags, startId);
          }else
              return  Service.START_NOT_STICKY;
      }
      


      3.调用stopService

      stopService(new Intent(ActivityC.this, ServiceB.class));
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        • 2012-03-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多