stopSelf()vs stopSelf(int)vs stopService(Intent)

Gio*_*nJh 42 service android

是什么在呼唤的差别
stopSelf(),stopSelf(int)或者stopService(new Intent(this,MyServiceClass.class))
里面onStartCommand()

例如,如果我以这种方式两次启动相同的服务:

...
Intent myIntent1 = new Intent(AndroidAlarmService.this, MyAlarmService.class);
myIntent1.putExtra("test", 1); 
Intent myIntent2 = new Intent(AndroidAlarmService.this, MyAlarmService.class);
myIntent2.putExtra("test", 2);
startService(myIntent1);
startService(myIntent2);
...
Run Code Online (Sandbox Code Playgroud)

并以这种方式实现onStartCommand:

public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "onStartCommand called "+intent.getIntExtra("test", 0), Toast.LENGTH_LONG).show();
stopService(new Intent(this,MyAlarmService.class));
return START_NOT_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

我得到了与三种方法完全相同的行为,即onDestroy仅在onStartCommand执行两次后才会被调用.

Sou*_*ech 79

我希望这能帮到您:

已启动的服务必须管理自己的生命周期.也就是说,系统不会停止或销毁服务,除非它必须恢复系统内存并且服务在onStartCommand()返回后继续运行.因此,服务必须通过调用stopSelf()来自行停止,或者另一个组件可以通过调用stopService()来停止它.

一旦请求使用stopSelf()或stopService()停止,系统将尽快销毁服务.

但是,如果您的服务同时处理对onStartCommand()的多个请求,那么您在处理启动请求时不应该停止服务,因为您可能已经收到了一个新的启动请求(在第一个结束时停止)请求将终止第二个).要避免此问题,可以使用stopSelf(int)来确保停止服务的请求始终基于最新的启动请求.

也就是说,当您调用stopSelf(int)时,将传递停止请求所对应的启动请求的ID(传递给onStartCommand()的startId).然后,如果服务在您能够调用stopSelf(int)之前收到新的启动请求,则ID将不匹配,服务将不会停止.


sco*_*ttt 34

这是一个简化的描述:

  • stopSelf()用于始终停止当前服务.

  • stopSelf(int startId)也用于停止当前服务,但startId是上次启动服务时指定的ID时.

  • stopService(Intent service) 用于停止服务,但从服务外部停止.

这是参考页面.


MKJ*_*ekh 5

所有 3 种方法的核心功能都相同,这就是它们具有相似名称的原因。它们之间存在非常小的差异。

  • public final void stopSelf()

班级:这属于android.app.Service班级

调用自:此方法仅用于从服务内部调用。

行为:服务将停止。onDestroy()状态调用。

  • public final void stopSelf(int startId)

班级:这属于android.app.Service班级

调用自:此方法仅用于从服务内部调用。

行为:旧版本中有一个方法 stopSelfResult(int startId)。此方法是该方法的较新版本。 当最近启动的时间是 startId 时,服务才会停止。onDestroy()状态调用。

可能您会发现此方法仅在您启动 2-3 个相同服务实例的情况下有用,但您想按照收到的 startId 列表存储的顺序停止它们。使用此方法时需要非常小心。

  • 公共抽象布尔停止服务(意图服务)

班级:这属于android.content.Context班级

调用自:此方法旨在从服务外部调用,尽管您可以从内部调用。

行为:如果服务未运行,则什么也不会发生。否则停止。请注意,对 startService() 的调用不计算在内——无论服务启动多少次,这都会停止服务。onDestroy()状态调用。