ProgressDialog仅在下载完成时显示

时间:2016-10-18 16:27:47

标签: android progressdialog android-broadcastreceiver android-intentservice downloadfile

我正在使用retrofit 2.0从服务器下载文件。我想显示一个显示下载进度的ProgressDialog。为此,我创建了IntentService来下载和编写文件以及BroadcastReceiver中的Activity来更新进度。

问题是ProgressDialog仅在下载完成后才会显示。 注意:我使用System.out.println来验证IntentServiceBroadcastReceiver之间的通信是否同步。

活动代码

public class ProjectListActivity extends Activity {


SvcApi svc;
LocalBroadcastManager bManager;
ProgressDialog mapDialog = null;
LocalBroadcastManager bManager;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.main_activity);



        mapDialog = new ProgressDialog(ProjectListActivity.this);
        getFile();
}
@Override
public void onResume() {
    super.onResume();
    registerReceiver();  // Registering my IntentService
}
public void onPause() {
    super.onPause();
    bManager.unregisterReceiver(broadcastReceiver); // Unregistering it 
}
private void registerReceiver(){

    bManager = LocalBroadcastManager.getInstance(this);
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction(Default_data.MESSAGE_PROGRESS);
    intentFilter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
    bManager.registerReceiver(broadcastReceiver, intentFilter);
 }
 private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        if(intent.getAction().equals(Default_data.MESSAGE_PROGRESS)){


                    Download download = intent.getParcelableExtra("download");
System.out.println(" - broadcastReceiver MESSAGE_PROGRESS " +
                            "-> download.getProgress = " + download.getProgress());

                    if(!mapDialog.isShowing()){

                        mapDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                        mapDialog.setMessage("Baixando Mapa Offline");
                        mapDialog.setProgress(0);
                        mapDialog.setMax(download.getTotalFileSize());
                        mapDialog.setProgress(download.getProgress());
                        mapDialog.show();
                        System.out.println(" - mapDialog.isshowing? " + mapDialog.isShowing());
                    }
                    else{
                        mapDialog.setProgress(download.getProgress());
                    }
               }
    }
};
    private void getFile(){
        Intent intent = new Intent(this,DownloadService.class);
        startService(intent);
    }
}

下载服务代码

public class DownloadService extends IntentService {

public DownloadService() {
    super("Download Service");
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }  // Using that avoid the StrictMode Exception
}

private int totalFileSize;
SvcApi svc;
long idproject;
@Override
protected void onHandleIntent(Intent intent) {

    idproject = intent.getLongExtra("idproject",0);
     initDownload(idproject);
}

private void initDownload(long idproject){


    svc = Svc.initDownload(this);
    if(svc != null){
        Call< ResponseBody> call = svc.getMap(idproject);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if (response.isSuccessful()) {
                    try {
                        downloadFile(response.body());
                    }catch(Exception e){
                            e.printStackTrace();
                    }
                } else {
                   int statusCode = response.code();
                   ResponseBody errorBody = response.errorBody();
                   Toast.makeText(getApplicationContext(), errorBody.toString(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                // handle execution failures like no internet connectivity
                Toast.makeText(
                        getApplicationContext(),
                        "Erro de Conectividade. Tentar mais tarde.",
                        Toast.LENGTH_SHORT).show();
            }
        });
    }
}

private void downloadFile(ResponseBody body) throws IOException {

    int count;
    byte data[] = new byte[1024 * 4];
    long fileSize = body.contentLength();
    InputStream bis = new BufferedInputStream(body.byteStream(), 1024 * 8);
    File mediaStorageDir = new File("/sdcard/osmdroid/");
    if (!mediaStorageDir.exists()) {
        System.out.println("- LocalFileManager.SaveMap.MkDir: /sdcard/osmdroid/? " + mediaStorageDir.mkdirs());
    }
    OutputStream outputStream = null;
    long total = 0;
    long startTime = System.currentTimeMillis();
    int timeCount = 1;
    outputStream = new FileOutputStream(mediaStorageDir.getPath() + "/tiles.zip");
    while ((count = bis.read(data)) != -1) {

        total += count;
        totalFileSize = (int) (fileSize / (Math.pow(1024, 2)));
        double current = Math.round(total / (Math.pow(1024, 2)));

        int progresss = (int) ((total * 100) / fileSize);

        long currentTime = System.currentTimeMillis() - startTime;

        Download download = new Download();
        download.setTotalFileSize(totalFileSize);

        if (currentTime > 1000 * timeCount) {

            download.setCurrentFileSize((int) current);
            download.setProgress(progresss);
            sendIntent(download);
            timeCount++;

        }

        outputStream.write(data, 0, count);
    }
    onDownloadComplete();
    outputStream.flush();
    outputStream.close();
    bis.close();


}


private void sendIntent(Download download){
    System.out.println("- DownloadService. Sending Intent.");
    Intent intent = new Intent(Default_data.MESSAGE_PROGRESS);
    intent.putExtra("download",download);
    LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcastSync(intent);

}

private void onDownloadComplete(){

    Download download = new Download();
    download.setProgress(100);
    sendIntent(download);

}

}

下载课程代码

公共类下载实现Parcelable {

public Download(){

}

private int progress;
private int currentFileSize;
private int totalFileSize;

public int getProgress() {
    return progress;
}

public void setProgress(int progress) {
    this.progress = progress;
}

public int getCurrentFileSize() {
    return currentFileSize;
}

public void setCurrentFileSize(int currentFileSize) {
    this.currentFileSize = currentFileSize;
}

public int getTotalFileSize() {
    return totalFileSize;
}

public void setTotalFileSize(int totalFileSize) {
    this.totalFileSize = totalFileSize;
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeInt(progress);
    dest.writeInt(currentFileSize);
    dest.writeInt(totalFileSize);
}

private Download(Parcel in) {

    progress = in.readInt();
    currentFileSize = in.readInt();
    totalFileSize = in.readInt();
}

public static final Parcelable.Creator<Download> CREATOR = new Parcelable.Creator<Download>() {
    public Download createFromParcel(Parcel in) {
        return new Download(in);
    }

    public Download[] newArray(int size) {
        return new Download[size];
    }
};
}

目录下载

    10-19 11:23:10.743 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:10.753 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 1
    10-19 11:23:10.773 30550-30550/palmaslab.com.palmap D/PhoneWindow: *FMB* installDecor mIsFloating : true
    10-19 11:23:10.773 30550-30550/palmaslab.com.palmap D/PhoneWindow: *FMB* installDecor flags : 8388610
    10-19 11:23:10.823 30550-30550/palmaslab.com.palmap I/System.out:  - mapDialog.isshowing? true
    10-19 11:23:11.744 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:11.744 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 6
    10-19 11:23:12.745 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:12.745 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 10
    10-19 11:23:13.836 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:13.836 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 14
    10-19 11:23:14.747 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:14.747 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 21
    10-19 11:23:15.788 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:15.788 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 26
    10-19 11:23:16.739 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:16.739 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 31
    10-19 11:23:17.750 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:17.750 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 37
    10-19 11:23:18.751 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:18.751 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 42
    10-19 11:23:19.742 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:19.742 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 47
    10-19 11:23:20.743 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:20.743 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 53
    10-19 11:23:21.744 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:21.744 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 58
    10-19 11:23:22.745 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:22.745 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 63
    10-19 11:23:23.766 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:23.766 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 68
    10-19 11:23:24.016 30550-30578/palmaslab.com.palmap I/art: Background partial concurrent mark sweep GC freed 43556(1837KB) AllocSpace objects, 2(2MB) LOS objects, 25% free, 8MB/11MB, paused 1.068ms total 126.617ms
    10-19 11:23:24.747 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:24.747 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 74
    10-19 11:23:25.758 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:25.758 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 79
    10-19 11:23:26.739 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:26.739 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 84
    10-19 11:23:27.740 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:27.750 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 89
    10-19 11:23:28.740 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:28.740 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 94
    10-19 11:23:29.751 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:29.751 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 99
    10-19 11:23:29.792 30550-30550/palmaslab.com.palmap I/System.out: - DownloadService. Sending Intent.
    10-19 11:23:29.792 30550-30550/palmaslab.com.palmap I/System.out:  - broadcastReceiver MESSAGE_PROGRESS -> download.getProgress = 100

0 个答案:

没有答案