异步任务2在doInBackground中运行

时间:2012-03-14 19:01:21

标签: android android-asynctask

您好我想使用异步任务,这是我的代码:

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();
             }
         }
    }  

我的问题是,如果我的InBackground函数返回字符串数组和位图,那么AsyncTask中的第三个参数应该是什么?有帮助吗?

2 个答案:

答案 0 :(得分: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");
  }
}

Bitmap是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());

答案 1 :(得分: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
       }
   }
}
相关问题