2013-03-12 63 views
0

我想在運行AsyncTask的'doInBackGround'方法時從mainthread中取消一個對話框。當我下載一張照片時,會彈出一個進度對話框,當它完成下載時,我會在onPostExecute中忽略()對話框。如果連接速度很慢,對話框會打開一段時間,直到出現超時錯誤或下載完成時,我才能取消它。如何使用後退按鈕,以便主線程可以訪問。這裏是我的代碼如下所示:如何在doInBackground在asynctask中運行時關閉對話框?

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> { 


    protected void onPreExecute() { 
     //this piece code doesn't seem to work 
     progressDialog = ProgressDialog.show(context, "", 
       "Image loading", true); 
    } 

    protected Bitmap doInBackground(String... urls) { 
     try { 
      InputStream in = new java.net.URL(urldisplay).openStream(); 
      mIcon11 = BitmapFactory.decodeStream(in); 
     } catch (Exception e) { 
      Log.e("Error", e.getMessage()); 
      e.printStackTrace(); 
     } 
     return mIcon11; 
    } 

    protected void onPostExecute(Bitmap result) { 
     //bmImage.setImageBitmap(result); 
     progressDialog.dismiss(); 
     someMethod(result); 

    } 
} 

回答

1

使用撤銷的進度對話框,傳遞一個取消收聽到進度對話框和取消方法中的任務,如

protected void onPreExecute() { 
    progressDialog = ProgressDialog.show(activity, "Searching files", "Scanning...", true, true, 
      new DialogInterface.OnCancelListener() { 
       @Override 
       public void onCancel(DialogInterface dialog) { 
        // When dialog in cancelled, need to explicitly cancel task otherwise it keeps on running 
        cancel(true); 
       } 
      } 
    ); 

    progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); 
} 
0

你可以嘗試使用ProgressDialog這是cancelable。這是該方法的簽名: -

public static ProgressDialog show (Context context, CharSequence title, CharSequence message, boolean indeterminate, boolean cancelable) 
相關問題