【发布时间】:2017-07-14 07:55:56
【问题描述】:
我正在开发一个 Android 应用程序,这里我正在使用 ProgressBar ,为此我使用 runOnUiThread() 从 doInBackground() 制作 VISIBLE/GONE AsyncTask 的方法,除了doInBackground() 没有找到其他地方适合做VISIBLE/GONE ProgressBar来满足UI需求。
在这个编码场景中,ProgressBar 可见但不旋转,当我通过 Activity 的onCreate() 方法使 ProgressBar 可见时,它正在旋转。
我不明白为什么会这样,我访问了 Stackoveflow 上的一些帖子,他们说 UI 线程无法旋转 ProgressBar,因为它可用于处理其他任务,因此我无法找到其他的修复让它工作的方法。
所以请帮我解决这个问题。 这是我用来制作 VISIBLE/GONE ProgressBar 的代码。
@Override
protected String doInBackground(String... f_url) {
int count;
try {
zipfileName = f_url[1];
fUrl3 = f_url[2];
if (fUrl3.equals("DontDownloadZip")) {
return "DownloadSuccess";
} else {
Log.d("Downloading ", zipfileName);
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
// Hide ProgressBar after server connection .
runOnUiThread(new Runnable() {
@Override
public void run() {
tipLayout.setVisibility(GONE);
}
});
// Code to download a file .
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(MyBooks.screen
.getFilesDir().getAbsolutePath()
+ "/BookZips/"
+ f_url[1]);
byte data[] = new byte[1024];
long total = 0;
int counter = 0;
while ((count = input.read(data)) != -1) {
counter++;
total += count;
// Display ProgressBar when percentage is 99 .
if ((int) ((total * 100) / lenghtOfFile) == 99) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (!identifier1.equals("BookZips9Download"))
tipLayout.setVisibility(VISIBLE);
}
});
}
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
android.os.FileUtils.setPermissions(MyBooks.screen
.getFilesDir().getAbsolutePath()
+ "/BookZips/"
+ f_url[1], FileUtils.S_IRWXU | FileUtils.S_IRWXG
| FileUtils.S_IROTH | FileUtils.S_IWOTH
| FileUtils.S_IXOTH, -1, -1);
}
} catch (Exception e) {
e.printStackTrace();
return "DownloadFailed";
}
return "DownloadSuccess";
}
【问题讨论】:
-
可以在 AsyncTask 的 onPreExecute() 方法中看到。
标签: android android-layout android-progressbar