내 환경 설정 화면에서 환경 설정 중 하나를 클릭하면 인터넷에서 파일을 다운로드하는 서비스를 시작하고 싶습니다. 서비스가 이미 실행중인 경우 (파일 다운로드) 서비스를 중지해야합니다 (다운로드 취소).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()
을 즉시 트리거하는 것입니다. 그러나 로그에 따르면 여전히 HTTP 요청을 계속 볼 수 있기 때문에 onHandleIntent()
이 계속 실행 중입니다. Service
이 스레드 자체에서 실행되기 때문입니까? 아니면 제가 잘못하고 있습니까? stopService()
이 호출 될 때 onHandleIntent()
의 모든 항목이 즉시 중지되도록 (또는 적어도 중지 할 수 있도록) 어떻게 할 수 있습니까?
이'isStopped' 변수를 숨기려면'onDestroy'에서 true로 설정하는 것을 고려하십시오. – xorgate
isStopped 변수는 public이어야합니다. 코드 스 니펫은이를 개인용으로 설정합니다. – v01d