2014-09-22 20 views
2

我對於android有點新鮮,並陷入了一種情況,我不知道如何處理它。如何從後臺關閉進度對話框

這裏就是我想要做:

從活動開始我一些任務,並取得進展,對話,而任務完成的背景。 如果任務成功完成,我關閉活動並開始新的活動。

但是,如果在後臺我發現了一個異常,我想回到活動並關閉進度對話框,並顯示一個敬酒也許發生了一些異常。

從活動:

@Override 
public void onCreate(Bundle savedInstanceState) 
{ 
// my code 

// start Progress Dialog 
    showProgressDialog(); 
} 

public void showProgressDialog() 
{ 
    PD = new ProgressDialog(getActivity()); 
    PD.setMessage("Downloading....."); 
    PD.show(); 
} 

@Override 
public void onDestroy() 
{ 
    super.onDestroy(); 
    if (PD != null) 
    { 
     PD.dismiss(); 
     PD = null; 
    } 
} 

,並在後臺:

try 
{ 
    // perform some db tasks 
    // using AsyncTask 
} 
catch (Exception e) 
{ 
    if(e.getErrorCode() == 34) 
    { 
     // From here I want go back to Activity and close the Progress dialog 
     // and shows what error has occurred. 
    } 
} 

所以,如果發生異常如何,我想回去的活動並關閉進度的對話中,或者是還有什麼其他方式來做到這一點?

+0

更好的方法是使用異步任務,其方法非常適合您的問題情況。您可以在onPostExecute中檢查結果,並根據它們開始一個意圖 – Skynet 2014-09-22 08:06:58

回答

2

因爲我知道ProgressDialog是在你的UI線程中,而你不能在後臺線程中訪問它。爲什麼不使用AsyncTask呢?它很容易使用,並且您可以更輕鬆地處理它。例如:

class TestAsync extends AsyncTask<Void, Void, Void> { 

     private ProgressDialog mDialog; 
     private Boolean error = false; 

     @Override 
     protected void onPreExecute() { 

      mDialog = new ProgressDialog(TestActivity.this); 
      mDialog.setCancelable(false); 
      mDialog.show(); 

     } 

     @Override 
     protected Void doInBackground(Void... arg0) { 


      try { 
       // whatever you would like to do in background 
      } catch (Exception e) { 
       error = true; 
      } 

      return null; 
     } 

     protected void onPostExecute(Void... arg0) { 
      mDialog.dismiss(); 

      if (error) { 
       Toast.makeText(getApplicationContext(), 
         R.string.error, Toast.LENGTH_SHORT).show(); 
       return; 
      } else { 

       // whatever you would like to do after background 
      } 

     } 
    } 
1

假設AsyncTask是一個內部類,你聲明的ProgressDialog的活動,你可以簡單地返回,並駁回onPostExecute是在UI線程運行它:

假設你的AsyncTask返回一個字符串

catch (Exception e) 
{ 
    if(e.getErrorCode() == 34) 
    { 
     // From here I want go back to Activity and close the Progress dialog 
     // and shows what error has occurred. 
     return "34" 
    } 
} 



public void onPostExecute(String result) { 
    // dismiss 
    // show result 
} 
0

如果任務花費很長時間,您不應該在UI上運行它。您應該使用異步任務。

你也應該經常檢查對話框ref是否仍然存在。

if(dialog!=null && dialog.isShowing()) 
    dialog.dismiss(); 

確保異步任務在同一個類上運行,否則使用弱引用來監聽任務的後期響應。