在我的首选项屏幕中,我想启动一项服务,以便在单击某个首选项时从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