当前位置: 代码迷 >> Android >> 如何把onStartCommand里返回了START_REDELIVER_INTENT的Servcie停止掉
  详细解决方案

如何把onStartCommand里返回了START_REDELIVER_INTENT的Servcie停止掉

热度:43   发布时间:2016-04-27 22:34:39.0
怎么把onStartCommand里返回了START_REDELIVER_INTENT的Servcie停止掉?
一个Servcie的onStartCommand里返回了START_REDELIVER_INTENT,是因为如果这个Service被系统Kill了或者app被Kill了,Service还能自动重启。

但是现在用户如果修改参数后再次点击“启动服务按钮”,我需要关闭上一次启动的Service,重新传Intent再开启一个新的Service。但是因为这个Servcie返回的是START_REDELIVER_INTENT,Servcie停止后又会启动?加上新开的就是2个,再点就又多一个。

怎么既能保证始终有一个Servcie在后台,又不会出现重复的Service?

启动Servcie的Activity

public class mainactivity extends Activity{
btn_start.setOnClickListener(new Button.OnClickListener() {
  @Override
public void onClick(View arg0) {
           Intent Intent1 = new Intent(this, bbService.class);
                             //我现在先停上次启动的Servcie,再重新开启
           this.stopService(Intent1);
           this.startService(Intent1);
                         }
                 }
}


Service

public class bbService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
                Client mClient = new Client(this, mgeo);
                //这里返回START_REDELIVER_INTENT,那每次停止Servcie后都会再启动一个新的。
                //那这个Servcie就不会停止了,用户会启动多个相同的Service
return START_REDELIVER_INTENT;
}
}

------解决思路----------------------
想办法设计成单子模式