您好我正在开发一款应用程序,首次启动应用程序时需要下载量非常大(100-200MB)。
我的第一个活动是启动一项服务,该服务具有执行所有下载的asynctask。
为了显示我的下载进度,我正在执行以下操作:
首先使用AsyncTask的publishProgress / onProgressUpdate我使用当前进度向我的活动发送广播:
@Override
protected Void doInBackground(Void... params) {
...
publishProgress(Integer.toString(completedFiles), current_filename, Integer.toString(file_progress));
...
}
@Override
protected void onProgressUpdate(String... progress) {
super.onProgressUpdate(progress);
progressBroadcast.putExtra(NOTIFY_DOWNLOAD_PROGRESS, progress);
sendOrderedBroadcast(progressBroadcast, null);
}
在我的活动上,我有一个更新进度条的BroadcastReceiver
private class ProgressReceiver extends BroadcastReceiver{
private int totalFiles;
public ProgressReceiver(Context context) {
progressDialog = new ProgressDialog(context);
}
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(ResourceDownloadService.NOTIFY_DOWNLOAD_START.equals(action)){
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setCancelable(false);
progressDialog.setTitle(getString(R.string.loading_res_dialog_title));
totalFiles = intent.getIntExtra(ResourceDownloadService.TOTAL_FILES, 0);
progressDialog.setMessage("Downloading Resources");
progressDialog.show();
}else if(ResourceDownloadService.NOTIFY_DOWNLOAD_END.equals(action)){
//Hide progress bar one we are done
progressDialog.dismiss();
startIntroActivity();
}else{
String[] progress_info = intent.getExtras().getStringArray(ResourceDownloadService.NOTIFY_DOWNLOAD_PROGRESS);
int completedFiles = Integer.parseInt(progress_info[0]);
String filename = progress_info[1];
int progress = Integer.parseInt(progress_info[2]);
progressDialog.setProgress(progress);
progressDialog.setMessage("Downloading "+filename +"\n"+completedFiles +" files downloaded of "+totalFiles);
}
}
}
所以我不确定我在这里做错了什么,因为几秒后进度条显示我得到一个ANR。
可能是因为我发送过多广播来更新进度条吗?
答案 0 :(得分:1)
我唯一能想到的是ANR是由于进度对话框长时间禁用交互,请尝试删除对话框并使用其他方法通知用户进度。
像这样的东西
public interface Listener {
public abstract void onEvent();
}
在广播接收器中创建静态引用和setter
私有静态MessageListener mListener = null;
@Override
public void onReceive(Context context, Intent intent) {
//stuff
if(mListener != null)
mListener.onEvent();
}
public static void setListener(Listener l) {
mListener = l;
}
然后在Activity
中实现监听器class MyActivity implements Listener{
@Override
public void onResume(){
//register the listener so that when the activity is visible it can receive updates
BroadCastReceiver.setListener(this);
}
@Override
public void onPause(){
//unregister the listener so the activity doesn't receive updates while in the background
BroadCastReceiver.setListener(null);
}
@Override
public void onEvent(){
//update the UI
}
}