经验丰富的程序员,但对Android / Java还是陌生的。我一直在学习AsyncTask,并认为我了解大多数功能,但对GET方法的用法有疑问。
在等待结果时似乎阻塞了线程。这不是否定使用AsyncTask的全部意义吗?我怀疑它一定有我不明白的目的。
我读过的所有书籍或其他资源都没有给出如何/何时/是否使用它的示例。我知道我可以使用onPostExecute来获取结果集,并且很可能是我要采用的路线,但是我想知道get()的用例是什么?
感谢您的启发。
public void button1Clicked(View v){
AsyncTask<Void, Void, String> MyTask = new MyTask();
log("Test 1. About to execute");
try {
MyTask.execute(); // This version returns immediately
} catch(Exception e){
e.printStackTrace();
}
log("Test 1. Back from execute");
}
public void button2Clicked(View v){
AsyncTask<Void, Void, String> MyTask = new MyTask();
log("Test 2. About to execute");
try {
String result = MyTask.execute().get(); // This version waits here, blocking the UI
log("Result=" + result);
} catch(Exception e){
e.printStackTrace();
}
log("Test 2. Back from execute");
}
class MyTask extends AsyncTask<Void, Void, String> {
@Override protected String doInBackground(Void... params){
log("doInBackground started");
try { // Sample long running task here
for(int i=0; i< 3; i++){
log("Tick: " +i);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
log("doInBackground completed");
return "done";
}
}
public void log(String message){
Log.i("DEB:" +Thread.currentThread().getName(), message);
}
---按下按钮1时记录---
DEB:main: Test 1. About to execute
DEB:main: Test 1. Back from execute
DEB:AsyncTask #1: doInBackground started
DEB:AsyncTask #1: Tick: 0
DEB:AsyncTask #1: Tick: 1
DEB:AsyncTask #1: Tick: 2
DEB:AsyncTask #1: doInBackground completed
---按下按钮2时记录---
DEB:main: Test 2. About to execute
DEB:AsyncTask #2: doInBackground started
DEB:AsyncTask #2: Tick: 0
DEB:AsyncTask #2: Tick: 1
DEB:AsyncTask #2: Tick: 2
DEB:AsyncTask #2: doInBackground completed
DEB:main: Result=done
DEB:main: Test 2. Back from execute