服务重新传递意图奇怪的行为?

Service redeliver intent strange behavior?

我正在使用 START_REDELIVER_INTENT 的服务,我想通过该服务将视频和视频附带的一些元数据上传到服务器。

据我所知,我需要使用 START_REDELIVER_INTENT 而不是 START_STICKY,因为第一个将尝试再次从意图中获取数据,而我需要这些数据。

我注意到发生的事情是它正确地将视频及其元数据上传到我的服务器,但它会在接下来的 1-2 天内再次随机重新上传。

我没有多次测试这种行为,但它已经发生了 4-5 次。难道我做错了什么 ?我是否应该在我的 Service 中添加一些内容以在它成功上传我的数据时将其标记为正确,这样它就不会重新传送?

我的代码:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    MyApplication.get(this).applicationComponent().inject(this);

    getIntentValues(intent);

    buildNotification();

    return START_REDELIVER_INTENT;
}

private void getIntentValues(Intent intent) {
// Here I get some strings from the intent ... 
}

private void buildNotification() {
    Notification.Builder builder = new Notification.Builder(this);
    builder.setSmallIcon(R.drawable.ic_action_search);
    builder.setContentTitle("Upload");
    builder.setContentText("Thank you for uploading!");
    builder.setPriority(Notification.PRIORITY_MIN);

    Notification notification = builder.build();

    // Start the Service in the Foreground
    startForeground(NOTIFICATION_ID, notification);

    Thread taskThread = new Thread(new UploadVideoTask());
    taskThread.start();

}

视频上传成功后,您需要通过stopSelf(startId)停止服务。

否则服务会在系统停止后重新启动,接收初始意图并重新上传视频。

仔细阅读对START_REDEVLIVER_INTENT的描述:

if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then it will be scheduled for a restart and the last delivered Intent re-delivered to it again via onStartCommand(Intent, int, int). This Intent will remain scheduled for redelivery until the service calls stopSelf(int) with the start ID provided to onStartCommand(Intent, int, int). The service will not receive a onStartCommand(Intent, int, int) call with a null Intent because it will will only be re-started if it is not finished processing all Intents sent to it (and any such pending events will be delivered at the point of restart).