在我的偏好设置屏幕中,当单击偏好设置中的一个选项时,我希望启动一个服务来从互联网下载文件。如果该服务已经运行(正在下载文件),则应停止服务(取消下载)。
服务类:
(注:该段为标题,无需翻译)
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
本身在一个线程中运行,还是我做错了什么?如何确保在调用stopService()
时onHandleIntent()
中的所有内容立即停止(或至少能够停止)?
isStopped
变量,考虑在onDestroy
中将它设置为true。 - xorgate