2015-01-27 3 views
0

많은 게시물과 의사를보고 읽었습니다. 하나는 몇 가지를 삽입 할 수 있습니다 이해합니다 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

+0

'cancel()'메소드는 쓰레드가 인터럽트되어야 하는지를 지정하는 boolean 인자를 취하는데, 이것은 실행중인 모든 I/O 연산을 중단시킬 것이다. – corsair992

답변

1

취소 방법은 공개되어 있으므로 무시할 수 있습니다. 사용자 지정 구현에서 먼저 기본 버전을 호출 한 다음 보류중인 http 연결을 중단 할 수 있습니다. cancel은 아마도 GUI 스레드에서 호출되기 때문에주의해야합니다.하지만 작동해야한다고 생각합니다.

+0

나는 일반적인 생각을 얻는다. 하지만 그것은 2 가지를 의미합니다. asynctask를 실행 한 활동 범위 수준에서 https 연결에 대한 참조를 보유해야합니다. 둘째, 주기적으로 점검 할 해결책이 없다는 것을 알 수 있습니까? – Poutrathor

+0

활동 클래스에 해당 참조를 배치 할 필요가 없으며 구현할 취소 메소드가 AsyncTask에 있습니다. 당신의 AsyncTask 구현 클래스에'HttpURLConnection urlConnection = null; '을 옮깁니다. IMO에는 정기적 인 취소 확인이 필요하지 않습니다. – marcinj

+0

"구현할 취소 방법은 AsyncTask에 있습니다"ofc, 나는 어리 석다. 사용자의 의지에 따라 작업을 다시 시작할 수 있기를 원하기 때문에 주기적으로 확인해야합니다. doInBackground()는 완료 될 때까지 또는 개발자가 isCancelled() {break}를 삽입 할 때까지 계속 실행됩니다. 그리고 취소 된 것이 종료되기 전에 다음 AsynTask가 시작되지 않는 것 같습니다 (취소 된 것은 종료됩니다. 그러나 여전히 doInBackground를 실행합니다) – Poutrathor

관련 문제