我使用以下代码从android
上的服务器下载文件下载活动代码:
public class DownloadActivity extends AppCompatActivity {
ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
progressDialog = new ProgressDialog(this);
progressDialog.setIndeterminate(false);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMax(100);
progressDialog.setCancelable(false);
progressDialog.show();
String url = "https://www.google.com.sa/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png";
String fileName = url.substring(url.lastIndexOf('/') + 1);
Intent intent = new Intent(DownloadActivity.this, DownloadService.class);
intent.putExtra("url", "https://www.google.com.sa/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png");
intent.putExtra("filename", fileName);
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);
}
private class DownloadReceiver extends ResultReceiver {
public DownloadReceiver(Handler handler) {
super(handler);
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
Log.d("PROGRESS", String.valueOf(progress)); // Here works well
progressDialog.setProgress(progress); // Here is the problem
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
}
代码工作符合预期,但progressDialog.setProgress(progress);
没有显示任何内容
Log.d()
在日志中显示的输出符合预期。
我不知道问题是什么?
答案 0 :(得分:1)
正如我在第一篇评论中提到的那样尝试使用处理程序,你的工作线程的构造函数(我假设)正在获取。您可以访问它,因为您编写了super(处理程序)。
将此代码放在您希望更新进度对话框的位置。
handler.post(new Runnable() {
@Override
public void run() {
progressDialog.setProgress(progress);
}
});
答案 1 :(得分:0)
感谢所有帮助过我的人,亲爱的@Anton Makov
private class DownloadReceiver extends ResultReceiver {
Handler mhandler ;
public DownloadReceiver(Handler handler) {
super(handler);
mhandler = handler;
}
@Override
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
final int progress = resultData.getInt("progress");
Log.d("PROGRESS", String.valueOf(progress));
mhandler.post(new Runnable() {
@Override
public void run() {
progressDialog.setProgress(progress);
}
});
if (progress == 100) {
progressDialog.dismiss();
}
}
}
}
这是最终的解决方案