IntentService STICKY被破坏,但服务在Android 2.3.4中记录数据

pol*_*kyg 1 android sticky android-intent android-service intentservice

我有一个Android应用程序.在一个活动中,我开始这样的服务:

Intent startIntent = new Intent(_context, HandlingService.class);
_context.startService(startIntent);
Run Code Online (Sandbox Code Playgroud)

HandlingService定义如下:

public class HandlingService extends IntentService
Run Code Online (Sandbox Code Playgroud)

然后在HandlingService里面我有这个:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, startId, startId);
    Log.v(ApplicationName,"HandlingService.onStartCommand");
    if ((flags & START_FLAG_RETRY) == 0){
        Log.v(ApplicationName,"Service is restarting");
    }
    return START_STICKY;
}
Run Code Online (Sandbox Code Playgroud)

还有这个:

@Override
protected void onHandleIntent(Intent sourceIntent) {
    Log.v(ApplicationName, "HandlingService.onHandleIntent");
    sendSomething(); 
}
Run Code Online (Sandbox Code Playgroud)

最后:

protected void sendSomething() {
    while (numberOfTry > 0) {
        numberOfTry++;
        Log.v(ApplicationName,"HandlingService.sending Something. Try# " + numberOfTry);
    }
}
Run Code Online (Sandbox Code Playgroud)

numberOfTry从1开始.

然后从启动服务的活动中,当我点击取消按钮时,我称之为:

Intent stopIntent = new Intent(CallingActivity.this, HandlingService.class);
CallingActivity.this.stopService(stopIntent);
Run Code Online (Sandbox Code Playgroud)

我看到被调用的HandlingService.OnDestroy,但我一直看到日志中有"HandlingService.sending Something.Try#"和越来越多的数字.

问题:如果我已经通过调用stopService来停止它,为什么它会保持活动状态?

提前致谢!吉列尔莫.

Dav*_*ser 7

用于IntentService文件明确规定,你应该覆盖onStartCommand()在你的派生类.你可能搞乱了内部的机制IntentService.

要么直接派生你的类,Service要么使用IntentService已经给你的框架(用于启动/停止自己).

  • `IntentService`有自己的启动/停止语义.它启动一个工作线程,处理它在队列中的工作,并在完成后自行停止.您不需要覆盖任何内容.它只是记录在案.如果您不喜欢它的工作方式,您只需创建自己的服务,扩展"服务"."IntentService"已经提供的启动/停止语义有什么问题?你想做什么不能使用`IntentService`的默认行为? (2认同)
  • 然后你不想使用`IntentService`.只需实现扩展`Service`的服务. (2认同)