在我的首选项屏幕中,我想在单击其中一个首选项时启动一项服务以从 Internet 下载文件。如果服务已在运行(下载文件),则应停止服务(取消下载)。
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()
使用 no AsyncTask
。它直接HttpURLConnection
用 a保存FileOutputStream
。
当我单击首选项时,服务正确启动。现在的问题是,当我点击停止服务时stopService()
,立即DownloadService
触发onDestroy()
;但是根据日志,onHandleIntent()
它仍在运行,因为我仍然可以连续看到 HTTP 请求。这是因为Service
在线程本身中运行,还是我做错了什么?如何确保在被调用onHandleIntent()
时立即停止(或至少能够停止)中的所有内容?stopService()