2013-07-26 51 views
0

我寫了下面的代碼的主類中的異步工人異步工人崩潰應用

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

     @Override 
     protected Void doInBackground(Void... params) { 
      // TODO Auto-generated method stub 

       Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show(); 
      return null; 
     } 





     protected void onProgressUpdate(Integer... progress) { 

     } 

     protected void onPostExecute(Long result) { 

     } 
    } 

但是調用這個崩潰的應用程序

public void render(View v) 
    { 
     new Renderer().execute(); 
    } 

有人能告訴我什麼錯?

回答

1

你不能在doInBackgroundToast,你會得到Can't create handler inside thread that has not called Looper.prepare()

如果僅僅是在這個階段進行測試(您的代碼似乎暗示),那麼現在就考慮寫一些日誌輸出。

或者把你的Toast要麼onPreExecuteonPostExecute

更多信息:How to raise a toast in AsyncTask, I am prompted to used the Looper

+0

即使在Onpostexecute.App中放置烤麪包後也不起作用 – techno

+0

您的'AsyncTask'錯誤。把'@ Override'放在所有的方法之前,並遵循eclipse告訴你做的事情。 'onPostExecute()'根本就沒有被調用,因爲方法簽名應該是'protected void onPostExecute(Void result){'根據你的'AsyncTask'聲明。 **短回答**:將onPostExecute更改爲'(Void result)'NOT'(Long result)'並且它將工作 –

0

您在doInbackground中顯示烤麪包,這是不可能的。這樣做在onPostExecute

protected void onPostExecute(Long result) { 
      Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show(); 
    } 

doInbackground調用在後臺線程。您應該在ui線程上更新ui。您可以在onProgressUpdate上顯示烤麪包。在

http://developer.android.com/reference/android/os/AsyncTask.html

更多信息檢查下4個步驟部分的話題。

+0

好吧,但即使在Onpostexecute.App中放置烤麪包後也不工作 – techno

0

您不能從後臺線程訪問UI線程。

0

AsyncTaskThreadsHandlers的幫手。它可以幫助您執行後臺任務並定期更新UI。

因此,AsyncTask運行的不同Threads方法: doInBackground在後臺線程中運行 onProgressUpdateonPostExecute在UI Thread運行。

現在,您只能修改UI Thread(=主Thread)中的UI。這就是爲什麼你的代碼會導致崩潰。只需將Toast轉換爲onPostExecute即可解決您的問題。

0
runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
        Toast.makeText(getApplicationContext(), "works... ", Toast.LENGTH_LONG).show(); 
        } 
       });` 

嘗試在主線程上做所有的UI工作。