2014-06-12 32 views
-1

建立連接時,有時可能會發生錯誤或者wifi可能被關閉。所以在這些情況下,我想向用戶顯示Toast消息。在AsyncBackground中顯示「Toast」的好方法

所以,我想是這樣的:

protected String doInBackground (String ... args) { 
    QircAccount account = new MyAccount(getApplicationContext()); 
    try { 
     acceptable = MyManager.INSTANCE.getService().getAcceptable(account.getUsername(), account.getAuthToken(), recId); 
    } 
    catch (RetrofitError re) { 
     Response r = re.getResponse(); 
     if (r!=null && r.getStatus() == 403) { 
      isLoggedIn = false; 
     } 
     if (re.isNetworkError()) { 
      Toast.makeText(getBaseContext(), "Connectivity problem.", Toast.LENGTH_SHORT).show(); 
     } 
    } 

但是,這給出了一個錯誤,如:

Can't create handler inside thread that has not called Looper.prepare() 

問題

  • 所以最好在onPostExecute顯示吐司消息?
  • 如何將消息「連接問題」傳遞給onPostExecute

回答

0
So its best to show Toast message in onPostExecute? 

是的,這是因爲在UI線程onPostExecute運行。

永遠不要在另一個線程中調用Toast.makeText,只有創建它的線程將成爲唯一可以調用/更新它的線程。因此您仍然可以通過調用UI線程runOnUiThread來調用/更新其他線程。

How should I pass the message "connectivity problem" to onPostExecute? 

只返回一個字符串在doInBackground因爲它返回一個字符串。在onPostExecute

@Override 
    protected void onPostExecute(String result) 
    { 
     Toast.makeText(getBaseContext(), result, Toast.LENGTH_SHORT).show(); 
    } 
+0

沒有我需要檢查'onPostExecute'字符串,看它是否顯示 「連接問題」 ?否則,在每個onPostExecute中,用戶將看到一個Toast ...即使操作成功。 – birdy

+0

@birdy然後不返回它,通過調用UI線程調用它 –

1

if (re.isNetworkError()) { 
     return "Connectivity problem."; 
    } 

,你總是可以做

runOnUiThread(new Runnable() { 
    public void run() { 
     Toast.makeText(.....).show(); 
    } 
}); 
+0

我認爲現在對我來說是最好的,因爲我在'doInBackground'中有很多Toast的活動 – birdy

+1

@birdy不要這樣做。你只是在問問題。 'AsyncTask'具有更新'UI'的方法。使用'onProgressUpdate()'如果你仍然有工作要做,如果沒有,然後使用'onPostExecute()' – codeMagic

+0

@codeMagic哪個麻煩呢? –