把一个对象处理程序消息对象、消息、程序

2023-09-05 02:26:07 作者:三天茬線,兩天上網

我需要从互联网上下载的图像, 在不同的线程, 然后发送该图像对象在处理程序中的消息,给UI线程。

I need to download an image from the internet, in a different thread, and then send that image object in the handler message, to the UI thread.

我已经有这样的:

...
Message msg = Message.obtain();

Bundle b = new Bundle();
b.putParcelable("MyObject", (Parcelable) object);
msg.setData(b);

handler.sendMessage(msg);

当我收到此消息, 我想提取的对象:

And when I receive this message, I want to extract the object:

...
public void handleMessage(Message msg) {
    super.handleMessage(msg);

    MyObject objectRcvd = (MyObject) msg.getData().getParcelable("IpTile");
    addToCache(ipTile);
    mapView.invalidate();
}

但是,这是给我:

But this is giving me:

...java.lang.ClassCastException...

谁能帮助?

Can anyone help?

顺便说一下,这是最有效的方式 传递对象到UI线程?

And by the way, is this the most efficient way to pass an object to the UI Thread?

感谢大家!

推荐答案

我会用一个AsyncTask的进行这种操作。它可以让你挂接到您的UI线程像的最新进展,一旦你完成你的下载。下面的例子显示了一种应该怎么做:

I would use an AsyncTask for this kind of operation. It allows you to hook into your ui thread for things like progress updates and once you have finished your download. The example below shows how one should be done:

class GetImageTask extends AsyncTask<String, int[], Bitmap> {

  @Override
  protected Bitmap doInBackground(String... params) {
    Bitmap bitmap = null;

    // Anything done here is in a seperate thread to the UI thread 
    // Do you download from here

    // If you want to update the progress you can call
    publishProgress(int progress); // This passes to the onProgressUpdate method

    return bitmap; // This passes the bitmap to the onPostExecute method
  }

  @Override
  protected void onProgressUpdate(Integer... progress) {
    // This is on your UI thread, useful if you have a progressbar in your view
  }

  @Override
  protected void onPostExecute(Bitmap bitmapResult) {
    super.onPostExecute(bitmapResult);
    // This is back on your UI thread - Add your image to your view
    myImageView.setImageBitmap(bitmapResult);
  }
}

希望帮助