我想品牌的AsyncTask類做後臺更新調用者線程的進展,但調用者線程!=的UI線程。 我試過這段代碼,但行publishProgress(i)似乎沒有效果。 有人可以告訴我如何解決它(或者我可以使用其他類)。 在此先感謝=)Asynctask一個UI線程
public class MainUI extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.button).setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Thread t=new Thread(){
boolean exit=false;
public void run(){
Looper.prepare();
new DownloadFilesTask().execute();
while (!exit){
try {
Thread.sleep(600);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.d("","Exit thread");
Looper.loop();
}
public void exit(){
exit=true;
}
class DownloadFilesTask extends AsyncTask<Void, Long, Long> {
protected Long doInBackground(Void... urls) {
long i=0;
for (i=0;i<20;i++){
Log.d("",i+" ");
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
publishProgress(i);
}
return i;
}
protected void onProgressUpdate(Long... progress) {
Log.d("Test",progress[0]+"");
}
protected void onPostExecute(Long result) {
exit();
}
}
};
t.start();
}
});
}
}
更新的鏈接:http://android-developers.blogspot.com/2009/05/painless-threading.html – dhaag23