2012-03-14 69 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());