2012-03-14 67 views
2
運行

你好,我想使用異步任務,這是我的sceleton代碼:異步任務2個功能doInBackground

public class MyActivity extends Activity { 
    private ProgressDialog pd = null; 
    private Object data = null; 

    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     // Show the ProgressDialog on this thread 
     this.pd = ProgressDialog.show(this, "Working..", "Downloading Data...", true, false); 

     // Start a new thread that will download all the data 
     new DownloadTask().execute("Any parameters my download task needs here"); 
    } 

    private class DownloadTask extends AsyncTask<String, Void, Object> { 
     protected Object doInBackground(String... args) { 
      Log.i("MyApp", "Background thread starting"); 

      // This is where you would do all the work of downloading your data 

      return "replace this with your data object"; 
     } 

     protected void onPostExecute(Object result) { 
      // Pass the result data back to the main activity 
      MyActivity.this.data = result; 

      if (MyActivity.this.pd != null) { 
       MyActivity.this.pd.dismiss(); 
      } 
     } 
    } 

我的問題是什麼應該是在的AsyncTask的第三個參數如果我將做InBackground函數返回一個字符串數組和一個位圖?任何幫助?

回答

2

我不認爲有從AsyncTask返回兩件事的支持。你可以使用一個簡單的內部類,用於容納返回的數據:

public class MyActivity ... { 
    class DownloadTaskResult { 
     String stringResult; 
     Bitmap bitmapResult; 
    } 

    class DownloadTask ... extends AsyncTask<String, Void, DownloadTaskResult> { 
     protected DownloadTaskResult doInBackground(String... args){ 
      //your work; return a DownloadTaskResult with the String and Bitmap you want 
     } 
    } 
} 
+0

我不知道這是不是最好的辦法來解決這個問題,但無論如何它應該工作。 – Fishbreath 2012-03-14 19:16:00

+0

以及如何訪問字符串結果?如果我的temp是DownloadTaskResult,我可以寫temp.stringResult嗎? – 2012-03-14 22:48:59

+0

是的。這就是說,Torid的答案是一個更一般的解決方案,如果更復雜的話。 – Fishbreath 2012-03-15 02:41:16

4

你可以使用一個軟件包(見http://developer.android.com/reference/android/os/Bundle.html)。所以,你的AsyncTask將看起來像......

public class MyTask extends AsyncTask<Void, Void, Bundle> 
{ 
    @Override 
    protected Bundle doInBackground(Void... arg) 
    { 
    Bundle bundle = new Bundle(); 
    bundle.putParcelable("Bitmap", bitmap); 
    bundle.putString("String", string); 

    return bundle; 
    } 
    protected void onPostExecute(Bundle bundle) 
    { 
    Bitmap bitmap = bundle.getParcelable("Bitmap"); 
    String string = bundle.getString("String"); 
    } 
} 

位圖是Parcelable,但你可能會遇到的所有運行時錯誤,但最小的位圖。所以,你可能需要把它變成一個字節數組,然後再返回,這樣的事情...

ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); 
byte[] bytes = baos.toByteArray(); 
Bundle bundle = new Bundle(); 
bundle.putByteArray("Bytes", bytes); 

這...

byte[] bytes = bundle.getByteArray("Bytes"); 
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, new BitmapFactory.Options());