android ondestroy service,android – 在onDestroy()之后仍然运行的IntentService onHandleIntent()...
在我的首選項屏幕中,我想啟動一項服務,以便在點擊其中一個首選項時從互聯網上下載文件.如果服務已在運行(下載文件),則應停止服務(取消下載).
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.它直接使用FileOutputStream保存HttpURLConnection.
單擊首選項時,服務正確啟動.現在的問題是,當我點擊停止服務時使用stopService(),DownloadService立即觸發了onDestroy();但是根據日志,onHandleIntent()仍在運行,因為我仍然可以連續看到HTTP請求.這是因為Service本身在一個線程中運行,還是我做錯了什么?當調用stopService()時,如何確保onHandleIntent()中的所有內容立即停止(或至少能夠停止)?
總結
以上是生活随笔為你收集整理的android ondestroy service,android – 在onDestroy()之后仍然运行的IntentService onHandleIntent()...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 日历控件的android代码,Andro
- 下一篇: android+发邮件,Android发