2016-02-23 32 views
1

我想取消舊的意圖,並與最新的意圖如何停止Android系統從重新傳遞舊意向IntentService?

例如進行:

在我的MainActivity: -

for(int i=0 ; i<10; i++){ 
    Intent intent = new Intent(mContext,MService.class); 
    intent.putExtra("text", i); 
    mContext.startService(intent); 
} 

在我IntentService: -

public class MService extends IntentService{ 

private static final String TAG = "MService"; 

public MService() { 
    super(TAG); 
    setIntentRedelivery(true); 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 
    Log.d(TAG, "onCreate"); 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.d(TAG, "onStartCommand"); 
    return super.onStartCommand(intent, flags, startId); 
} 
@Override 
protected void onHandleIntent(Intent intent) { 
    Log.d(TAG,"onHandleIntent"); 
    Bundle bundle = intent.getExtras(); 
    String value = (String)(bundle.get("text")); 
    Log.d(TAG, "Received value---"+value); 
    SystemClock.sleep(2000); 
    } 
} 

而且我的日誌看起來像:

MService: onCreate 
    MService: onStartCommand 
    MService: onHandleIntent 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: Received value---0 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: onStartCommand 
    MService: Received new location 
    MService: onHandleIntent 
    MService: Received value---1 
    MService: onHandleIntent 
    MService: Received value---2 
    MService: onHandleIntent 
    MService: Received value---3 
    MService: onHandleIntent 
    MService: Received value---4 
    MService: onHandleIntent 
    MService: Received value---5 
    MService: onHandleIntent 
    MService: Received value---6 
    MService: onHandleIntent 
    MService: Received value---7 
    MService: onHandleIntent 
    MService: Received value---8 
    MService: onHandleIntent 
    MService: Received value---9 

我要處理,而不是處理2至8

+1

請介紹更多的細節您的問題的能力,創建自己的Service子你自己的版本。你的確切工作流程是什麼?您使用什麼方法啓動該服務?你也可以附上一些代碼。 – Blehi

回答

0

只看該IntentServicedocumentation最後意圖9(最新的),似乎是當startService(Intent)被稱爲(在你的代碼,它被稱爲在for循環中),Android會創建一個新的Worker線程。此工作線程然後處理Intent

請注意,清單中只有一個正在運行IntentService,根據< service>元素運行。如果您撥打startService() 10次,仍然最多隻有一個IntentService正在運行。命令將排隊並由onHandleIntent()

一次處理一個。IntentService類本身沒有提供用於取消先前意圖的API。

您可能需要創建的IntentService,你有自己的工作隊列,一個在那裏你必須取消指令