我正在使用后台服务来允许用户上传新的邮票,但是当用户关闭应用程序时,它会再次将邮票重新传送到服务器,而不是一次就是它,因此会产生多个重复...我该如何避免它,这是我正在使用的代码:
public class UploaderService extends Service {
/** indicates how to behave if the service is killed */
int mStartMode;
/** interface for clients that bind */
IBinder mBinder;
/** indicates whether onRebind should be used */
boolean mAllowRebind;
/** Called when the service is being created. */
@Override
public void onCreate() {
}
/** The service is starting, due to a call to startService() */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
final String title;
Bundle data = null;
if(intent.getExtras() != null) {
data = intent.getExtras();
}
if(data != null) {
title = data.getString("title");
UploadSessionManager uploadSessionManager = new UploadSessionManager(this);
uploadSessionManager.createUploadSession(title);
} else {
UploadSessionManager uploadSessionManager = new UploadSessionManager(this);
HashMap<String, String> uploadMap = uploadSessionManager.getUserDetails();
title = uploadMap.get("title");
}
ApiManager.getAsyncApi().addStamp(title, new Callback<StampResponse>() {
@Override
public void success(StampResponse stampResponse, Response response) {
Toast.makeText(getApplicationContext(), "Service DONE", Toast.LENGTH_LONG).show();
UploadSessionManager uploadSessionManager = new UploadSessionManager(getApplicationContext());
uploadSessionManager.logoutUploadSession();
notifyUser("stampDone", stampResponse.get_id());
}
@Override
public void failure(RetrofitError error) {
throw error;
}
});
}
return START_REDELIVER_INTENT;
}
private void notifyUser(String itemDone, String itemId) {
Bundle extraData = new Bundle();
extraData.putString("itemId", itemId);
extraData.putString("itemDone", itemDone);
Intent intentWake = new Intent();
intentWake.putExtras(extraData);
intentWake.setAction("done");
intentWake.addCategory("done");
getApplicationContext().sendBroadcast(intentWake);
}
/** A client is binding to the service with bindService() */
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/** Called when all clients have unbound with unbindService() */
@Override
public boolean onUnbind(Intent intent) {
return mAllowRebind;
}
/** Called when a client is binding to the service with bindService()*/
@Override
public void onRebind(Intent intent) {
}
/** Called when The service is no longer used and is being destroyed */
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
ApiManager调用正在将数据发送到服务器,但是当返回响应时我想完全停止它,因为它已完成作业,但由于某种原因,它因为Start_redeliver_intent调用而再次重新发送数据,不确定怎么说工作已经完成,即使应用程序被用户关闭也不会重新启动它,这时它通常会再次重新发送数据。