Programing

AsyncTask : doInBackground ()의 반환 값은 어디로 가나 요?

lottogame 2020. 12. 5. 09:09
반응형

AsyncTask : doInBackground ()의 반환 값은 어디로 가나 요?


를 호출 할 때 AsyncTask<Integer,Integer,Boolean>반환 값은 다음과 같습니다.

protected Boolean doInBackground(Integer... params)?

일반적으로 AsyncTask를 시작 new AsyncTaskClassName().execute(param1,param2......);하지만 값을 반환하지 않는 것 같습니다.

의 반환 값은 어디 doInBackground()에서 찾을 수 있습니까?


그러면 결과 작업을 위해 재정의 할 수 있는 onPostExecute 에서 값을 사용할 수 있습니다.

다음은 Google 문서의 예제 코드 스 니펫입니다.

 private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
      protected Long doInBackground(URL... urls) {
          int count = urls.length;
          long totalSize = 0;
          for (int i = 0; i < count; i++) {
              totalSize += Downloader.downloadFile(urls[i]);
              publishProgress((int) ((i / (float) count) * 100));
          }
          return totalSize;
      }

      protected void onProgressUpdate(Integer... progress) {
          setProgressPercent(progress[0]);
      }

      protected void onPostExecute(Long result) {
          showDialog("Downloaded " + result + " bytes");
      }
 }

class doInBackground()get () 메서드를 호출하여 protected Boolean의 반환 값을 검색 할 수 있습니다 AsyncTask.

AsyncTaskClassName task = new AsyncTaskClassName();
bool result = task.execute(param1,param2......).get(); 

그러나 get()계산이 완료 될 때 까지 대기 하고 UI 스레드를 차단 하므로 UI의 응답성에주의하세요 .
내부 클래스를 사용하는 경우 onPostExecute (Boolean result) 메서드에서 작업을 수행하는 것이 좋습니다.

UI 만 업데이트하려는 경우 AsyncTask두 가지 가능성을 제공합니다.

  • 에서 실행 된 작업과 병렬로 UI를 업데이트하려면 doInBackground()(예 :을 업데이트 하려면) 메서드 내에서 ProgressBar호출해야합니다 . 그런 다음 메서드 에서 UI를 업데이트해야합니다 .publishProgress()doInBackground()onProgressUpdate()
  • 작업이 완료 될 때 UI를 업데이트하려면 onPostExecute()메서드 에서 수행해야합니다 .

    /** This method runs on a background thread (not on the UI thread) */
    @Override
    protected String doInBackground(String... params) {
        for (int progressValue = 0; progressValue  < 100; progressValue++) {
            publishProgress(progressValue);
        }
    }
    
    /** This method runs on the UI thread */
    @Override
    protected void onProgressUpdate(Integer... progressValue) {
        // TODO Update your ProgressBar here
    }
    
    /**
     * Called after doInBackground() method
     * This method runs on the UI thread
     */
    @Override
    protected void onPostExecute(Boolean result) {
       // TODO Update the UI thread with the final result
    }
    

    이렇게하면 반응 문제에 대해 신경 쓰지 않아도됩니다.

  • 참고URL : https://stackoverflow.com/questions/4489399/asynctask-where-does-the-return-value-of-doinbackground-go

    반응형