Explanation on the Use of Handle in Android Thread

  • 2021-11-02 02:12:15
  • OfStack

Android UI thread is not safe, UI operation in the sub-thread may lead to the collapse of the program. Solution: Create an Message object, then send it out with the help of Handler, and then in Handler handleMessage() Method to get the Message object you just sent, and then do the UI operation here so that there will be no more crashes

Defining class inheritance Handler


public class BallHandler extends Handler{
  ImageView imageview;
  Bitmap bitmap;
  public BallHandler(ImageView imageview,Bitmap bitmap){
    super();
    this.imageview=imageview;
    this.bitmap=bitmap;
  }
  public void handleMessage(Message msg){
      bitmap =(Bitmap)msg.obj;
      imageview.setImageBitmap(bitmap);
  }

In the thread, create an Message object and send a message to Handle


Message msg = new Message();
      msg.obj = bitmap;
      handler.sendMessage(msg);

Create an Handler object in the thread and then start the thread

Summarize


Related articles: