많은 게시물과 의사를보고 읽었습니다. 하나는 몇 가지를 삽입 할 수 있습니다 이해합니다 isCancelled(); 일부 코드 블록 사이. URL 가져 오기와 같은 부분으로 나눌 수없는 더 큰 작업량은 어떻습니까?AsyncTask의 doInBackground() 내에서 isCancelled()를 주기적으로 확인하고 필요한 경우 반환하는 방법은 무엇입니까?
해결책을 찾기 위해이 더미 프로젝트를 시도했습니다. asynctask가 작동하는 동안 isCancelled()를 주기적으로 검사하고 doInBackground()에 남아있는 모든 내용을 건너 뛰고 싶습니다.
@Override
protected Void doInBackground(Void... params) {
strUrlBase = "http://www.legorafi.fr/2012/12/20/portrait-benoit-le-fameux-ami-noir-de-tous-les-racistes/";
if (fgDebugLocal){Log.i(tagLocal, tagLocal + "strUrlBase = " + strUrlBase);};
timer = new Timer();
timer.scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {
if (isCancelled()) {
if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled true");};
timer.cancel();
return;
} else {
if (fgDebugLocal){Log.e(tagLocal, tagLocal + "timer asyncTask : isCancelled FALSE");};
}
}
},0, 100);
for (int i = 0; i<15; i++) {
HttpURLConnection urlConnection = null;
try {
url = new URL(strUrlBase);
https = (HttpURLConnection) url.openConnection();
https.setDoOutput(true);
urlConnection = https;
if (urlConnection.getInputStream() != null){ // Crash there :(
inputStream = new BufferedInputStream(urlConnection.getInputStream());
reader = new BufferedReader(new InputStreamReader(inputStream));
ByteArrayBuffer baf = new ByteArrayBuffer(50);
int current = 0;
while((current=reader.read())!=-1){
baf.append((byte)current);
}
strJson = new String (baf.toByteArray());
if (fgDebugLocal){Log.i(tagLocal, tagLocal + "check le gorafi number "+i+" - " + strJson.substring(0, 100));};
https.disconnect();
} else {
if (fgDebugLocal){Log.i(tagLocal, "urlConnection.getInputStream() != null");};
fgErrorConn = true;
varResultRequest = -1;
}
} catch (IOException e) {
if (fgDebugLocal){Log.i(tagLocal, "IOException = "+e.getMessage());};
fgErrorPb = true;
varResultRequest =0;
//publishProgress(100);
}
}
varResultRequest = 1;
return null;
}
은 TimerTask를 올바르게의 isCancelled() 값을 감지하지만 그 후 행동 할 수있는 방법을 찾을 수 없습니다 :
나는이 시도. 어떤 생각? 또는 다른 방법으로?Ty
'cancel()'메소드는 쓰레드가 인터럽트되어야 하는지를 지정하는 boolean 인자를 취하는데, 이것은 실행중인 모든 I/O 연산을 중단시킬 것이다. – corsair992