ProgressDialog在新线程之前没有启动

时间:2016-12-06 12:09:55

标签: android progress-bar

我尝试将文件加载到服务器。我需要等待所有操作完成后才能启动enother方法。所以我使用同步调用。我尝试在开始新线程之前显示ProgressDialog,但是,虽然所有线程都没有完成我的UI线程只是卡住了。

private void uploadImageSync() {
    final ProgressDialog progressDialog;
    progressDialog = new ProgressDialog(BarcodActivity.this);
    progressDialog.setMessage("Load...");
    progressDialog.show();

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(ROOT_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RequestInterface service = retrofit.create(RequestInterface.class);

    int i=0;
    while (i++ <= 4) {
        File f = getOutputMediaFilePath(mCode + "_"+i, true);
        if(f.exists()){
            RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f);

            MultipartBody.Part body = MultipartBody.Part.createFormData("file", f.getName(), requestFile);

            final Call<ResponseBody> resultCall = service.uploadImage(body);

            Thread t = new Thread(new Runnable() {
                public void run() {
                    try {
                        resultCall.execute().body();
                     } catch (IOException e) {
                        e.printStackTrace();
                    }
                }});
            t.start();
            try {
                t.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    progressDialog.dismiss();
}

3 个答案:

答案 0 :(得分:1)

您的UI线程冻结的原因是您正在调用t.join()。您的UI Thread等待新Thread完成。

相反,您可以使用AsyncTask,因为该类是为此类任务而制作的。

以下是有关如何使用它和android dev guide

的一般示例
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
     protected Long doInBackground(URL... urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {
             totalSize += Downloader.downloadFile(urls[i]);
             publishProgress((int) ((i / (float) count) * 100));
             // Escape early if cancel() is called
             if (isCancelled()) break;
         }
         return totalSize;
     }
 protected void onProgressUpdate(Integer... progress) {
     setProgressPercent(progress[0]);
 }

 protected void onPostExecute(Long result) {
     showDialog("Downloaded " + result + " bytes");
   }
 }

new DownloadFilesTask().execute(url1, url2, url3);

请注意,onPostExecute在UI线程上运行,因此您可以轻松地将其解除。

答案 1 :(得分:0)

你的UI线程在t.join()行被阻止为https://docs.oracle.com/javase/tutorial/essential/concurrency/join.html提及:

  

join方法允许一个线程等待另一个线程的完成。

只需调用start方法即可运行您的主题。

答案 2 :(得分:0)

private class DownloadFileTask extends AsyncTask<Void, Void, Void> {

    private ProgressDialog progressDialog = null;
    private WeakReference<Activity> weakReference = null; 

    public DownloadFileTask(Activity activity) {
        reference = new WeakReference<>(activity);
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog = new ProgressDialog(weakReference.get());
        progressDialog.setMessage("Load...");
        progressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ROOT_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        RequestInterface service = retrofit.create(RequestInterface.class);

        int i=0;
        while (i++ <= 4) {
            File f = getOutputMediaFilePath(mCode + "_"+i, true);
            if(f.exists()){
                RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), f);
                MultipartBody.Part body = MultipartBody.Part.createFormData("file", f.getName(), requestFile);
                final Call<ResponseBody> resultCall = service.uploadImage(body);
                resultCall.execute().body();
            }
        }
        return null;
    }

    @Override
    protected void onCancelled() {
        super.onCancelled();
        if(weakReference != null)
            weakReference.clear();
       weakReference = null;

        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
        progressDialog = null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        if(weakReference != null)
            weakReference.clear();
        weakReference = null;

        if (progressDialog != null && progressDialog.isShowing())
            progressDialog.dismiss();
        progressDialog = null;
    }
}