从同一服务的多个实例停止服务

时间:2014-03-31 16:11:31

标签: android android-intent service

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

    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中使用了alarmmanager。 MyAlarm创建通知。

例如。我设定了11.30和11.40的警报。我希望删除11.40的警报。所以我按下停止按钮。但两个警报都被取消了

1 个答案:

答案 0 :(得分:0)

这是因为没有运行同一服务的多个实例,调用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