在我的首選項屏幕中,我想啓動一項服務,以便在單擊某個首選項時從Internet上下載文件。如果服務已經在運行(下載文件),那麼服務應該停止(取消下載)。InDestroy onHandleIntent()仍然在onDestroy()後運行
public class Setting extends PreferenceActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
downloadPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
@Override
public boolean onPreferenceClick(Preference pref) {
if (DownloadService.isRunning) {
Setting.this.stopService(new Intent(Setting.this,
DownloadService.class));
} else {
Setting.this.startService(new Intent(Setting.this,
DownloadService.class));
}
return false;
}
});
}
}
服務類:
public class DownloadService extends IntentService {
public static final int DOWNLOAD_SUCCESS = 0;
public static final int DOWNLOAD_FAIL = 1;
public static final int DOWNLOAD_CANCELLED = 2;
public static final int SERVER_FAIL = 3;
public static boolean isRunning = false;
private int result;
public DownloadService() {
super("DownloadService");
}
@Override
public void onCreate() {
super.onCreate();
isRunning = true;
}
@Override
protected void onHandleIntent(Intent intent) {
if (NetworkStateUtils.isInternetConnected(getApplicationContext()))
result = downloadFiles(getApplicationContext());
}
@Override
public void onDestroy() {
super.onDestroy();
switch (result) {
case DOWNLOAD_SUCCESS:
Toast.makeText(getApplicationContext(), R.string.download_finished,
Toast.LENGTH_SHORT).show();
break;
case DOWNLOAD_CANCELLED:
Toast.makeText(getApplicationContext(), R.string.download_canceled,
Toast.LENGTH_SHORT).show();
break;
case DOWNLOAD_FAIL:
Toast.makeText(getApplicationContext(), R.string.download_failed,
Toast.LENGTH_SHORT).show();
break;
}
isRunning = false;
}
}
這項服務是爲了運行,直到下載完畢。功能downloadFiles()
不使用AsyncTask
。它直接保存HttpURLConnection
與FileOutputStream
。
當我點擊首選項時,服務開始正確。現在問題是,當我點擊停止stopService()
服務時,DownloadService
立即觸發onDestroy()
;但根據日誌,onHandleIntent()
仍在運行,因爲我仍然可以持續看到HTTP請求。這是因爲Service
在線程本身運行,還是我做錯了什麼?我如何確保onHandleIntent()
中的所有內容在調用stopService()
時立即停止(或至少能夠停止)?
爲了隱藏這個'isStopped'變量,可以考慮在'onDestroy'中將其設置爲true – xorgate
isStopped變量必須是公共的。代碼片段將其設置爲私有。 – v01d