【问题标题】:Stopping a service from multiple instances of the same service从同一服务的多个实例停止服务
【发布时间】:2014-03-31 16:11:30
【问题描述】:

我正在制作一个闹钟应用程序。我使用意图启动服务。

    public void Start(View view) {
    hr = timePick.getCurrentHour();
    min = timePick.getCurrentMinute();
    service = new Intent(this,MyService.class);
    Bundle bundle = new Bundle();
    bundle.putInt("HOUR", hr);
    bundle.putInt("MIN", min);
    service.putExtras(bundle);
    startService(service);

}

我通过

停止服务
    public void Stop(View view) {
    hr = timePick.getCurrentHour();
    min = timePick.getCurrentMinute();
    Intent myAlarm = new Intent(this, MyAlarm.class);
    Intent myService = new Intent(this, MyService.class);
    Bundle bundle = new Bundle();
    bundle.putInt("HOUR", hr);
    bundle.putInt("MIN", min);
    myService.putExtras(bundle);
    myAlarm.putExtras(bundle);
    stopService(myAlarm);
    stopService(myService);
}

我可能有多个正在运行的服务实例。但是,当我尝试通过传递小时和分钟来停止服务的单个实例时,服务的所有实例都将停止。我在服务 MyService 中使用了警报管理器。 MyAlarm 创建通知。

例如。我设置了 11.30 和 11.40 的闹钟。我想删除 11.40 的闹钟。所以我按下停止按钮。但是两个警报都被取消了

【问题讨论】:

    标签: android android-intent service


    【解决方案1】:

    那是因为没有运行同一服务的多个实例这样的事情,调用startService(intent) 不会启动它只是再次调用onStartCommand 的服务的另一个实例

    来自文档

    Multiple requests to start the service result in multiple corresponding calls to the service's onStartCommand(). However, only one request to stop the service (with stopSelf() or stopService()) is required to stop it.

    http://developer.android.com/guide/components/services.html

    【讨论】:

      猜你喜欢
      • 2011-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-23
      • 1970-01-01
      • 2010-11-19
      • 2013-05-26
      相关资源
      最近更新 更多