关于android的多线程问题,这样写对吗?


我想用这样的方法来一边展示一个圆型的ProgressDialog,一边执行一些操作。但是这样写起来的话,在操作执行的时候,ProgressDialog不转动,效果很不好,应该怎么写?

   
  pd = ProgressDialog.show(GridLayoutActivity.this, "","...");
  
new Thread(new Runnable() {
public void run() {
someFunc();
handler.sendEmptyMessage(0);// 执行耗时的方法之后发送消给handler
}
}).start();

Android 多线程

夜魅D小调 12 years, 8 months ago

在android中一般用轻量级的异步 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");
}
}

在doInBackground中做异步的操作,异步执行完了就执行onPostExecute。

hecate answered 12 years, 8 months ago

Your Answer