我有一个带有类WifiAudioActivity的 android 应用程序,它扩展了 Activity 类。
简而言之,当按下应用程序上的按钮时,会运行一个方法,该方法使用进度条来显示该方法的进度。
我显示进度条并使用AsyncTasks更新它。
问题是,为了获取方法的进度,我让它在另一个线程上运行,所以AsyncTask线程上的 while 循环可以不断地作为更新的进度值并将其显示在进度条中。但是,当我调用更新进度条的progessUpdate()时,在我在运行的线程上设置方法后,它不会更新进度条,甚至不会跳转到onProgressUpdate()方法代码。
有趣的是,我可以在使用该方法运行 Thread 之前使用虚拟值更新进度。
我认为这是我的线程有问题 - 有人可以帮忙吗?
private ProgressDialog downloadAllDialog;
private ProgressDialog usingDialog;
private int totalDownloadSize;
private Download downloadAll;
private int totalBlocksLeft;
private boolean downloadComplete;
private boolean downloadFailed;
public void downloadAllClick(View view) //When the download all button is clicked
{
new PerformTask().execute();
}
private class PerformTask extends AsyncTask<Void, Integer, Integer>
{
protected void onPreExecute()
{
showDialog();
}
protected Integer doInBackground(Void... voi)
{
int retryCount = 0;
downloadComplete = false; //Assume the download is not complete
downloadFailed = false;
totalBlocksLeft = 0;
progressUpdater.run(); //Running method thread
publishProgress(20); //THIS DOES NOT WORK
while ((retryCount < Consts.RETRY_TOTAL) && (!(downloadComplete)))
{
int blocksDownloaded = 0;
while ((downloadComplete == false) && (downloadFailed == false))
{
blocksDownloaded = totalDownloadSize - downloadAll.getTotalBlocksLeft(); //GOT FROM THE RUNNING THREAD METHOD
publishProgress(blocksDownloaded); //DOES NOT WORK
}
...
}
return totalBlocksLeft ;
}
Thread progressUpdater = new Thread()
{
@Override
public void run()
{
downloadComplete = downloadAll.downloadAudio(totalBlocksLeft); //Download the audio
if (!(downloadComplete))
{
downloadFailed = true;
}
}
};
protected void onProgressUpdate(Integer... progress)
{
usingDialog.setProgress(progress[0]);
}
protected void onPostExecute(Integer result)
{
removeDialog();
}
}
protected Dialog onCreateDialog()
{
downloadAllDialog = new ProgressDialog(this);
downloadAllDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
downloadAllDialog.setMax(totalDownloadSize);
downloadAllDialog.setProgress(0);
downloadAllDialog.setMessage("Download All");
usingDialog = downloadAllDialog;
return downloadAllDialog;
}
}
就目前而言,在代码的关键位中:
blocksDownloaded = totalDownloadSize - downloadAll.getTotalBlocksLeft(); //GOT FROM THE RUNNING THREAD METHOD
publishProgress(blocksDownloaded); //DOES NOT WORK
blocksDownloaded,它从线程运行方法中获取其更新的值,正在随着进度进行更新。我确信这在技术上是不正确的,但是在 AsyncTask 中拥有线程确实会运行该方法,同时在 main 方法中获取进度更新。因此,只有进度条的更新不起作用。