我想为 AsyncTask 类打上品牌,以便在后台执行一些操作,以进度更新调用者线程,但使用 UI 线程的调用者线程 != 。 我已经尝试过该代码,但publishProgress(i)行似乎没有效果。 有人可以告诉我如何修复它(或者我可以使用其他什么类)。 提前致谢 =)
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();
}
});
}
}
最佳答案
创建线程来启动 ASyncTask 是没有用的,不应该这样做。 您应该阅读 Android 开发者网站上的无痛线程文档
http://android-developers.blogspot.com/2009/05/painless-threading.html
关于java - Asynctask 输出 UI 线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6635511/