Android : AsyncTask의 onPreExecute ()에 전달 변수를 전달하는 방법은 무엇입니까?
AsyncTask
내부 클래스로 구현 한로드 작업에를 사용합니다 .
에서 onPreExecute()
나는 다음에 다시 숨길 로딩 대화 상자를 보여줍니다 onPostExecute()
. 그러나 일부 로딩 작업의 경우 매우 빨리 완료 메시지 로딩 대화 상자를 표시하고 싶지 않습니다.
수있는 부울 전달할 매개 변수로 이것을 나타내려고 onPreExecute()
했지만 어떤 이유로 onPreExecute()
든 매개 변수를 사용하지 않는을 구석으로 같습니다.
명백한 해결 방법은 아마도 모든 AloadTask 또는 외부 클래스에서 멤버를 사용할 것입니다. 더 좋은 방법이 있습니까?
생성 가능한 재정의 할 수 있습니다. 다음과 같은 것 :
private class MyAsyncTask extends AsyncTask<Void, Void, Void> {
public MyAsyncTask(boolean showLoading) {
super();
// do stuff
}
// doInBackground() et al.
}
그런 다음 작업을 호출 할 때 다음과 같은 작업을 수행하십시오.
new MyAsyncTask(true).execute(maybe_other_params);
편집 : 작업 호출을 단순화하기 때문에 멤버 변수를 만드는 것보다 유용합니다. 위의 코드를 다음과 비교하십시오.
MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();
1) 저에게 그것은 말하는 작업에 매개 변수 를 전달하는 가장 간단한 방법입니다.
// To call the async task do it like this
Boolean[] myTaskParams = { true, true, true };
myAsyncTask = new myAsyncTask ().execute(myTaskParams);
다음과 같이 선언하고 사용하십시오.
private class myAsyncTask extends AsyncTask<Boolean, Void, Void> {
@Override
protected Void doInBackground(Boolean...pParams)
{
Boolean param1, param2, param3;
//
param1=pParams[0];
param2=pParams[1];
param3=pParams[2];
....
}
2) 전달하는 것이 작업에 메소드를 전달하는 인프라 (스레드, 메시지 전달 등)를 여러 번 코딩하지면 사용에서 실행해야하는 메소드를 전달 변수로 전달하는 것이 좋습니다. 다음 예제는 접근 방식을 간략하게 설명합니다. 또한 생성자에서 초기화 변수를 전달하기 위해 async-task를 서브 클래시해야 할 수도 있습니다.
/* Generic Async Task */
interface MyGenericMethod {
int execute(String param);
}
protected class testtask extends AsyncTask<MyGenericMethod, Void, Void>
{
public String mParam; // member variable to parameterize the function
@Override
protected Void doInBackground(MyGenericMethod... params) {
// do something here
params[0].execute("Myparameter");
return null;
}
}
// to start the asynctask do something like that
public void startAsyncTask()
{
//
AsyncTask<MyGenericMethod, Void, Void> mytest = new testtask().execute(new MyGenericMethod() {
public int execute(String param) {
//body
return 1;
}
});
}
Asynctask <>에 전달되는 이유, 방법 및 매개 변수는 여기를 참조 하십시오 . 최고의 설명이라고 생각합니다.
Google의 Android 문서에 따르면 다음과 같습니다.
비동기 작업은 Params, Progress 및 Result라는 3 가지 일반 유형과 onPreExecute, doInBackground, onProgressUpdate 및 onPostExecute라는 4 단계로 정의됩니다.
AsyncTask의 일반 유형 :
비동기 작업에 사용되는 세 가지 유형은 다음과 같습니다.
실행시 태스크에 전송되는 매개 변수의 유형 인 매개 변수. 진행률, 백그라운드 계산 중에 게시 된 진행률 단위의 유형입니다. 결과, 백그라운드 계산 결과의 유형입니다. 모든 유형이 항상 비동기 작업에서 사용되는 것은 아닙니다. 유형을 미사용으로 표시하려면 Void 유형을 사용하면됩니다.
private class MyTask extends AsyncTask<Void, Void, Void> { ... }
추가로 참조 할 수 있습니다 : http://developer.android.com/reference/android/os/AsyncTask.html
또는 Sankar-Ganesh의 블로그를 참조하여 AsyncTask의 역할을 지울 수 있습니다.
일반적인 AsyncTask 클래스의 구조는 다음과 같습니다.
private class MyTask extends AsyncTask<X, Y, Z>
protected void onPreExecute(){
}
이 메서드는 새 스레드를 시작하기 전에 실행됩니다. 입력 / 출력 값이 없으므로 변수 또는 필요한 작업을 초기화하면됩니다.
protected Z doInBackground(X...x){
}
AsyncTask 클래스에서 가장 중요한 메서드입니다. 백그라운드에서하고 싶은 모든 작업을 메인 스레드와 다른 스레드에 배치해야합니다. 여기에 입력 값으로 "X"유형의 객체 배열이 있고 (헤더에 표시됩니까? "... extends AsyncTask"가 있습니다. 입력 매개 변수의 TYPES) 유형에서 객체를 반환합니다. "지".
protected void onProgressUpdate (Y y) {
}이 메서드는 publishProgress (y) 메서드를 사용하여 호출되며 일반적으로 백그라운드에서 수행중인 작업의 진행률을 표시하는 진행률 표시 줄과 같이 기본 화면에 진행률이나 정보를 표시하려는 경우에 사용됩니다.
보호 된 무효 onPostExecute (Z z) {
}이 메서드는 백그라운드에서 작업이 완료된 후 호출됩니다. 입력 매개 변수로 doInBackground 메소드의 출력 매개 변수를 수신합니다.
X, Y 및 Z 유형은 어떻습니까?
위의 구조에서 추론 할 수 있습니다.
X – The type of the input variables value you want to set to the background process. This can be an array of objects.
Y – The type of the objects you are going to enter in the onProgressUpdate method.
Z – The type of the result from the operations you have done in the background process.
외부 클래스에서이 작업을 어떻게 호출합니까? 다음 두 줄만 사용하면됩니다.
MyTask myTask = new MyTask();
myTask.execute(x);
여기서 x는 X 유형의 입력 매개 변수입니다.
작업이 실행되면 "외부"에서 상태를 확인할 수 있습니다. "getStatus ()"메소드 사용.
myTask.getStatus (); 다음 상태를받을 수 있습니다.
RUNNING-작업이 실행 중임을 나타냅니다.
PENDING-작업이 아직 실행되지 않았 음을 나타냅니다.
FINISHED-onPostExecute (Z)가 완료되었음을 나타냅니다.
AsyncTask 사용에 대한 힌트
onPreExecute, doInBackground 및 onPostExecute 메소드를 수동으로 호출하지 마십시오. 이것은 시스템에 의해 자동으로 수행됩니다.
다른 AsyncTask 또는 Thread 내에서 AsyncTask를 호출 할 수 없습니다. 메소드 execute의 호출은 UI 스레드에서 수행되어야합니다.
onPostExecute 메서드는 UI 스레드에서 실행됩니다 (여기서는 다른 AsyncTask를 호출 할 수 있습니다!).
태스크의 입력 매개 변수는 Object 배열이 될 수 있습니다. 이렇게하면 원하는 오브젝트와 유형을 넣을 수 있습니다.
태스크 생성자에서 또는 execute를 호출 할 때 매개 변수를 전달할 수 있습니다.
AsyncTask<Object, Void, MyTaskResult>
첫 번째 매개 변수 (Object)는 doInBackground에서 전달됩니다. 세 번째 매개 변수 (MyTaskResult)는 doInBackground에 의해 리턴됩니다. 원하는 유형으로 변경할 수 있습니다. 세 개의 점은 0 개 이상의 개체 (또는 개체의 배열)가 인수로 전달 될 수 있음을 의미합니다.
public class MyActivity extends AppCompatActivity {
TextView textView1;
TextView textView2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
textView1 = (TextView) findViewById(R.id.textView1);
textView2 = (TextView) findViewById(R.id.textView2);
String input1 = "test";
boolean input2 = true;
int input3 = 100;
long input4 = 100000000;
new MyTask(input3, input4).execute(input1, input2);
}
private class MyTaskResult {
String text1;
String text2;
}
private class MyTask extends AsyncTask<Object, Void, MyTaskResult> {
private String val1;
private boolean val2;
private int val3;
private long val4;
public MyTask(int in3, long in4) {
this.val3 = in3;
this.val4 = in4;
// Do something ...
}
protected void onPreExecute() {
// Do something ...
}
@Override
protected MyTaskResult doInBackground(Object... params) {
MyTaskResult res = new MyTaskResult();
val1 = (String) params[0];
val2 = (boolean) params[1];
//Do some lengthy operation
res.text1 = RunProc1(val1);
res.text2 = RunProc2(val2);
return res;
}
@Override
protected void onPostExecute(MyTaskResult res) {
textView1.setText(res.text1);
textView2.setText(res.text2);
}
}
}
'IT' 카테고리의 다른 글
유닉스의 'ls'이름순 (0) | 2020.07.25 |
---|---|
C ++-std :: shared_ptr 또는 boost :: shared_ptr에 참조 전달 (0) | 2020.07.25 |
자바 펼쳐를 사용하여 링크를 만들려면 어떻게 사용합니까? (0) | 2020.07.25 |
DateTime에서 어떻게 딥 카피를 받습니까? (0) | 2020.07.25 |
각도 파일 업로드 (0) | 2020.07.25 |