2012-06-29 61 views
0

我正在使用asy任務來執行加載過程,而服務應該注意連接。 我正在上線的一些錯誤:錯誤Intent.putExtra AsyncTask

serviceIntent.putExtra("receiver",new DownloadReceiver(new Handler())); 

當我使用的AsyncTask和服務做的連接。 我的代碼是的AsyncTask是:

private class DownloadReceiver extends ResultReceiver{ 
public DownloadReceiver(Handler handler) { 
    super(handler); 
} 

@Override 
    protected void onReceiveResult(int resultCode, Bundle resultData) { 
    super.onReceiveResult(resultCode, resultData); 
    // if (resultCode == DownloadService.UPDATE_PROGRESS) { 
     int progress = resultData.getInt("progress"); 
    // mProgressDialog.setProgress(progress); 
    // if (progress == 100) { 
     //  mProgressDialog.dismiss(); 
     } 
    } 



    protected String doInBackground(String... params) { 

    Intent serviceIntent = new Intent(); 
      serviceIntent.putExtra("url", "www.google.com"); 

      new DownloadReceiver(new Handler()); 
      serviceIntent.putExtra("receiver",new DownloadReceiver(new Handler())); 
    serviceIntent.setAction("connection.DownloadService"); 
    context.startService(serviceIntent); 

有啥可問題?

+0

發佈錯誤給出的堆棧跟蹤。還可以詳細說明你想要達到的目標嗎?你爲實際嘗試做的事情提供了很少的背景。 – FoamyGuy

+0

給我們看堆棧跟蹤 – confucius

+0

你爲什麼要嘗試啓動一個'Service'來從'AsyncTask'的工作線程執行下載?這沒有意義。可以在'doInBackground()'中執行下載,或者直接從主「Activity」代碼啓動「Service」。 – Squonk

回答

1
if(this error == compile time error){ 
`DownloadReceiver` class should implements the Parcelable interface 
} 
else{ 

我想既然你正在創建的doInBackground()方法,在另一個線程比UI一個執行內部Handler對象你得到一個錯誤,然後在你的應用程序要訪問的UI Thread一些地方使用Handler對象 。注意:要正確地做到這一點,你應該在UI Thread中創建Handler。對你的情況來說,這是一個好的地方。

onPostExecute 

或將其作爲實例變量。並在構造函數中傳遞它;

}

2

假設你的意圖修改是正確的,那麼從的AsyncTask的doInBackground方法將你的Intent代碼 到onPostExecute功能。

您不能從doInBackground內部修改任何視圖,您必須在保證在事件派發線程上運行的其中一個回調函數中執行此操作。