Java android进度条未正确更新进度(onPostExecute()运行延迟)
我正在构建一个用于实践和学习的应用程序,用于从互联网下载文件。我确信我将来会对它进行很多更改,但是现在我在正确更新进度条方面遇到了困难。当我单击按钮时,一个AsyncTask子类应该运行并获取文件。进度条应该在从internet读取文件时更新。问题是,有时进度条似乎一次更新,立即更新,有时它会延迟很长时间保持空白,直到再次更新,一次更新。我发现使用buffer.size()作为publishProgress()的参数存在问题,但我不确定如何正确地执行此操作。onPostExecute()也需要很长时间才能运行。作为一个附带问题,我有一小段我注释掉的代码,它使用rxjava更新进度条。我正在考虑用类似这样的东西来替换onPostExecute()。这是个坏主意吗?这是“rxjava的正确用法”吗?以下是我的主要活动:Java android进度条未正确更新进度(onPostExecute()运行延迟),java,android,android-asynctask,reactivex,Java,Android,Android Asynctask,Reactivex,我正在构建一个用于实践和学习的应用程序,用于从互联网下载文件。我确信我将来会对它进行很多更改,但是现在我在正确更新进度条方面遇到了困难。当我单击按钮时,一个AsyncTask子类应该运行并获取文件。进度条应该在从internet读取文件时更新。问题是,有时进度条似乎一次更新,立即更新,有时它会延迟很长时间保持空白,直到再次更新,一次更新。我发现使用buffer.size()作为publishProgress()的参数存在问题,但我不确定如何正确地执行此操作。onPostExecute()也需要很
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MAIN";
private static final String startURL = "https://www.google.com";
private static final int REQUEST_CODE_EXTERNAL = 0;
private Button runButton;
private EditText urlSpecBox;
private ProgressBar progressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//request for permission to write to storage here
if(ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, (new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}), REQUEST_CODE_EXTERNAL);
}
progressBar = (ProgressBar) findViewById(R.id.progroessBar);
progressBar.setMax(100);
runButton = (Button) findViewById(R.id.dwnldButton);
runButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try{
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
new AsyncDownload(new URL(startURL), progressBar).execute();
}catch (MalformedURLException me){
Log.e(TAG, "error with url", me);
}
}
});
urlSpecBox = (EditText) findViewById(R.id.urlSpecBox);
}
}
和我的asynctask子类:
public class AsyncDownload extends AsyncTask<Void, Integer, Void>{
private static final String TAG = "AsyncDownload";
private static final String STORAGE_LOCATION = "/sdcard/"; //android directory picker is needed
private URL url;
private ProgressBar mProgessBar;
//private ArrayList<Byte> bytes = new ArrayList<>();
public AsyncDownload(URL url, ProgressBar progressBar){
mProgessBar = progressBar;
this.url = url;
}
@Override
protected void onProgressUpdate(Integer... progress){
mProgessBar.setProgress(progress[0]);
}
@Override
protected Void doInBackground(Void... params){
try{
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int c;
while ((c = in.read()) != -1){
buffer.write(c);
publishProgress(buffer.size());
}
Log.i(TAG, "response received");
Random rand = new Random(4L);
String temp = String.valueOf(rand.nextInt());
String finalLocation = STORAGE_LOCATION + temp;
File file = new File(finalLocation);
file.getParentFile().mkdirs();
Log.i(TAG, file.getName());
FileOutputStream fOut = new FileOutputStream(file);
fOut.write(buffer.toByteArray());
buffer.close();
fOut.flush();
fOut.close();
FileInputStream fIn = new FileInputStream(finalLocation);
String reRead = new String();
int a;
while ((a = fIn.read()) != -1){
reRead += a;
}
Log.i(TAG, "reRead" + reRead);
//this section is for automatic file naming
/*Random rand = new Random(5L);
String fileNumber = String.valueOf(rand.nextInt());
StringBuilder sb = new StringBuilder();
sb.append(fileNumber).append("download"); //definitely needs work
Log.i(TAG, sb.toString());*/
//FileOutputStream fOut = new FileOutputStream()
}catch (IOException ioe){
Log.e(TAG, "network error" + ioe.toString(), ioe);
}
/*rx.Observable.just(0) //is it correct to use rxjava this way?
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
new Action1<Integer>() {
@Override
public void call(Integer integer) {
mProgessBar.setProgress(integer);
mProgessBar.setVisibility(View.VISIBLE);
}
}
);*/
return null;
}
@Override
protected void onPostExecute(Void result){ // METHOD IS NEVER CALLED
super.onPostExecute(result);
Log.i(TAG, "onPostExecute called! - Task Completed!");
mProgessBar.setProgress(0);
mProgessBar.setVisibility(View.GONE);
}
}
由于在循环中公开进程,所以会出现延迟,这会使主线程多次调用它。我们有一些解决方案:
FileOutputStream fOut = new FileOutputStream(file);
FileInputStream fIn = new FileInputStream(finalLocation);
byte data[] = new byte[4096];
long progress = 0;
int count;
int fileSize = connection.getContentLength();
while ((c = in.read()) != -1){
//we should write the data before publish progress
fOut.write(data, 0, count)
try{
Thread.sleep(100);
}catch (InterruptedException ie){
Log.e(TAG, "thread interrupted", ie);
}finally {
if (fileSize > 0){
publishProgress((int) ((progress+=count)*100/fileSize));
}
}
}
在AsyncDownload类中使用此选项
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
}
尝试从doInBackground方法返回字符串。因此,您可以在onPostExecute中检查任务是否已完成的状态。为什么不在AsyncTask中尝试
受保护的void onProgressUpdate
Class@AshutoshSagar你是说我应该打电话给ProgressUpdate吗?我确实在异步任务中覆盖了它。我需要打super.onProgressUpdate吗?或者我遗漏了什么?像这样progressupdate(Integer…progress){setProgressPercent(progress[0]);}
我只是不明白应该使用什么来进行进度和计数。我正在尝试将进程作为初始化为0的整数,但我不清楚从何处获取计数。我必须使用for循环来代替while吗?我发布了一个对我的代码的编辑,这是我试图遵循你的建议。似乎我做得不对,虽然滞后增加了。谢谢。根据你的建议,我能使它工作得更好。再次感谢。不过我还有一个问题。由于某种原因,connection.getContentLength返回-1。为了解决这个问题,我使用了一个静态整数作为文件大小。它工作得更好,但不是它应该的方式。你知道我怎样才能得到用于文件大小的正确值吗?如果你在onDoingBackground外部使用静态变量,无法与外部同步,我们必须检查connection.contentNL>0…@Override progressUpdate(Integer…progress){mProgessBar.setProgress(progress[0]);}
这就是我的用法。对吗?
if (fileSize > 0) {
currentProgress = ((progress += count) * 100 / fileSize);
// Publish only on increments of 1%
if (currentProgress >= previousProgress + 1) {
this.publishProgress(currentProgress);
previousProgress = currentProgress;
}
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
}