2013-04-12 2 views
2

글쎄, 난 http://developer.android.com/reference/android/os/AsyncTask.htmlandroid의 asyntask 매개 변수의 차이점은 무엇입니까? 내 질문이 말한대로

에 그것은 나에게

Asyntask <params, progress, result> 

을 알려줍니다하지만 난 진행을 사용하지 않은 참조하십시오. 당신의 합의에 따른 상태입니까? 또는 규칙이 있습니까?

예를 들어

: 나는,

class loadingdata extends AsyncTask<?,?,?> 
    protected void onPreExecute() {} 
    protected String doInBackground(String... args) {} 
    protected void onPostExecute() {} 

은 그래서

asyntask <void String void> ? 

로 3 매개 변수를 삽입해야하거나이 저를 도와주세요

<preExecute, postExecute, doInBackground> or so fourth? 

의 규칙이 이것에 초심자 및 나는 그것을 이해하지 않는다.

답변

3

다음 Void을 사용 (이 voidVoid하고하지 않도록 자본 V주의) . AsyncTask<params, progress, result> 시그니처에

는 첫번째 doInBackground()에 전달 어레이의 유형, 두 번째 onProgressUpdate() 호출 publishProgress() 호출 및 세번째 doInBackdround() 의해 반환에 전달되는 데이터 형식 인 경우 사용 된 배열의 유형이다 onPostExecute(). 비동기 작업이 3 개 일반적인 유형에 의해 정의된다

doInBackground(String... params) 
onProgressUpdate(Integer... progress) 
onPostExecute(Boolean result) 
0

AsyncTask에는 일반 매개 변수가 있으므로 은 모두이어야합니다. 당신이 그 중 하나를 사용하지 않는다면, 당신이 제공하는 유형은 정말로 중요하지 않습니다.

+0

하지만 어떻게 doInBackground가 어떤 상황에 있어야하는지 알 수 있습니까? 아니면 단순히 어떤 상황에 놓을 수 있으며 다른 2 개는 무효화 될 수 있습니까? 자동으로 걸릴까요? –

+0

@ user2198192 AsyncTask로 무엇을 달성하려고합니까? –

0

유형은 일반이므로 임의의 클래스 또는 기본 유형을 사용할 수 있습니다. AsyncTasks에있는 명령문을 실행하려면 AsyncTasks의 인스턴스를 작성한 다음 해당 인스턴스에 대해 execute()를 호출하십시오.

고토 : AsyncTask를 더 상세 사용 http://mysecretishelloworld.blogspot.in/2013/04/asynctask-usage-guide.html

.

0

http://developer.android.com/reference/android/os/AsyncTask.html

AsyncTask를의 일반적인 유형

비동기 작업에 사용되는 세 가지 유형의

은 다음과 같습니다

  1. 에 Params, 실행시 작업에 전송 된 매개 변수의 종류 .

  2. 진행률, 백그라운드 계산 중에 게시 된 진행률 단위의 유형입니다.

  3. 결과, 백그라운드 계산 결과의 유형.

모든 유형이 비동기 작업에서 항상 사용되는 것은 아닙니다. 유형을 사용하지 않는 것으로 표시하려면 다음 형식을 사용하십시오.

개인 클래스 MyTask extends AsyncTask {...당신이 AsyncTask 매개 변수 중 하나 이상 필요하지 않은 경우}

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)); 
     // Escape early if cancel() is called 
     if (isCancelled()) break; 
    } 
    return totalSize; 
} 

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

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

URL parameter for doInBackground(URL... urls) 
You call publishProgress((int)somevalue) in doinBackground() to update progress. 
Integer parameter for onProgressUpdate(Integer... progress) 
Long (result) parameter for onPostExecute(). The result is received from doInBackground().  

사용

new DownloadFilesTask().execute(url1, url2, url3); 
3

예를 들어

은 ...

private class MyAsyncTask extends AsyncTask<String, Integer, Boolean> 

... 방법 서명 될 것이라고 의미 ..., Params, Progress and Result라고하고, onPreExecute, doInBackground, onProgressUpdateonPostExecute이라고하는 4 단계.

AsyncTask를의 일반적인 유형 : 비동기 작업에서 사용

세 가지 유형은 다음과 같습니다 :

Params -> the type of the parameters sent to the task upon execution. 
Progress -> the type of the progress units published during the background computation. 
Result -> the type of the result of the background computation. 

모든 종류는 항상 비동기 작업에서 사용되는 것은 아닙니다. 사용하지 않는 등의 유형을 표시하려면 유형의 무효 사용

private class MyTask extends AsyncTask<Void, Void, Void> { ... } 

AsyncTask를하고 4 개 방법 구현 :이 방법에 간다 코드가 긴 작업을 실행 수행 :

1. doInBackground합니다. 버튼 클릭시 onClick 메서드가 실행되면 매개 변수를 받아들이는 execute 메서드를 호출하고 매개 변수가 전달 된 doInBackground 메서드를 자동으로 호출합니다.

2. onPostExecute :이 메소드는 doInBackground 메소드가 처리를 완료 한 후에 호출됩니다. doInBackground로부터의 결과가이 메소드에게 건네집니다.

3. onPreExecute :이 메서드는 doInBackground 메서드가 호출되기 전에 호출됩니다.

4. onProgressUpdate :이 메소드는 doInBackground에서 publishProgress를 호출하여 호출되며이 메소드를 호출합니다.

 Overriding onPostExecute, onPreExecute and onProgressUpdate is optional. 

기억해야 할 : 소스보기 인쇄 :

1. Instance of Async Task needs to be created in UI thread. As shown in onClick method a new instance of LongOperation is created there. Also execute method with parameters should be called from UI thread. 

    2. Methods onPostExecute, onPreExecute and onProgressUpdate should not be explicitly called. 

3. Task can be executed only once. 

우리가 아래에 AsyncTask를 확장하는 샘플 클래스 LongOperation, 보자?

private class LongOperation extends AsyncTask<String, Void, String> { 
    @Override 
    protected String doInBackground(String... params) { 
      // perform long running operation operation 
      return null; 
    } 
    /* (non-Javadoc) 
    * @see android.os.AsyncTask#onPostExecute(java.lang.Object) 
    */ 
    @Override 
    protected void onPostExecute(String result) { 
      // execution of result of Long time consuming operation 
    } 
    /* (non-Javadoc) 
    * @see android.os.AsyncTask#onPreExecute() 
    */ 
    @Override 
    protected void onPreExecute() { 
    // Things to be done before execution of long running operation. 
    //For example showing ProgessDialog 
    } 
    /* (non-Javadoc) 
    * @see android.os.AsyncTask#onProgressUpdate(Progress[]) 
    */ 
    @Override 
    protected void onProgressUpdate(Void... values) { 
      /* Things to be done while execution of long running operation 
      is in progress. 
      For example updating ProgessDialog */ 
      } 
    } 
관련 문제