【问题标题】:Android : stopservice from an activity that did not start itAndroid:从未启动的活动中停止服务
【发布时间】:2016-12-07 15:37:30
【问题描述】:

我有一个 App.java,它在 onCreate() 中启动 2 个服务。

我有一个 MainActivity,并且在 MainActivity 的 Log-Off 方法中,我需要停止这 2 个服务

我该怎么做?既然这个MainActivity没有启动这2个服务,那能不能停止呢?

【问题讨论】:

  • 这与从启动它们的 Activity 中的方式相同。使用stopService()
  • 在 onCreate() 中启动 2 个服务的 App.java 是否将 App 归类为 Activity?如果不是您知道,即使您停止服务,那么您的自定义 Application 类也必须在没有 em 的情况下生存?
  • @VladMatvienko 我需要阻止他们从 Activity 而不是从 App.java
  • 如我所说,您可以通过常规方式停止它。

标签: android


【解决方案1】:

你可以像这样直接使用stopService()

stopService(new Intent(MainActivity.this, YourService.class));

但正如seanhodgeshttps://stackoverflow.com/a/9665584/4758255 中所说,

从正在运行的服务中调用 stopSelf() 通常会更好 而不是直接使用 stopService() 。您可以在 AIDL 接口中添加一个 shutdown() 方法,该方法允许 Activity 请求调用 stopSelf()。

你可以使用EventBus来代替AIDL接口。

类似这样的:

public MyService extends IntentService {

  private boolean shutdown = false;

  public void doSomeLengthyTask() {
    // This can finish, and the Service will not shutdown before 
    // getResult() is called...
        ...
  }

  public Result getResult() {
    Result result = processResult();

    // We only stop the service when we're ready
    if (shutdown) {
       stopSelf();
    }

    return result;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    EventBus.getDefault().register(this);
  }

  @Override
  public void onDestroy() {
    EventBus.getDefault().unregister(this);
    super.onDestroy();
  }

  // This method receive the Event for stopping the service
  @Subscribe
  public void onMessageEvent(StopServiceEvent event) {
    shutdown = true;
  }
}

其中 StopServiceEvent 是一个简单的类:

public class StopServiceEvent {
}

您只需发送事件以从您的 MainActivity 停止服务:

EventBus.getDefault().post(new StopServiceEvent());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-02
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多