我有一個意向服務,下載幾千兆的視頻。我有一個「停止」按鈕,如果意外點擊「開始」或其他什麼來停止下載。我知道這已被問了幾次,但沒有爲我工作的答案。如何強制停止意向服務進行中?
我嘗試調用stopService()
,不能正常工作。那只是叫IntentService.OnDestroy()
。 我試着打電話給stopSelf()
內onDestroy
,也不管用。
我試着做一個像標誌一樣的東西,但是onHandleIntent如果它已經在運行,它不會被調用,它會等到當前的工作完成並執行。而且,即使這個會工作,我就必須有像一個巨大的if語句,即吸
是我唯一的選擇真的把它改寫到正規的服務?
//回答
public class SyncService extends IntentService {
boolean isCanceled;
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent.hasExtra("action")) {
// Set the canceling flag
isCanceled= intent.getStringExtra("action").equals("cancel");
}
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
// Clean up the possible queue
if (intent.hasExtra ("action")) {
boolean cancel = intent.getStringExtra ("action"). Equals ("cancel");
if (cancel) {
return;
}
}
...
Get your inputStream from HttpUrlConnection or whatever
...
while ((bytesRead = in.read(buffer)) > 0) {
if (isCanceled) {
isCanceled = false;
break;
}
...
}
}
}
而且隨着
Intent intent = new Intent(context, SyncService.class);
intent.putExtra("action", "cancel");
context.startService(intent);
你可以考慮從你的問題刪除您的解決方案,而是提供它作爲一個解決方案。 – jbaums