Handler和Message

1. handler和message

public class MainActivity extends AppCompatActivity {
    private Button button;
    private ImageView imageView;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            System.out.println(msg.arg1);
            imageView.setImageBitmap(msg.data);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = this.findViewById(R.id.button1);
        imageView = this.findViewById(R.id.imageView1);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new MyThread()).start();
            }
        });
    }
    public class MyThread implements Runnable {
        @Override
        public void run() {
            Message message = Message.obtain();
            // message.obj=data;
            //message.what=IS_FINSH;
            handler.sendMessage(message);
        }
    }

}

2.message

1.
  Message message = Message.obtain();
  message.obj=data;
  message.what=IS_FINSH;
  handler.sendMessage(message);
2.
  Message message = Message.obtain(handler);
  message.obj=data;
  message.what=IS_FINSH;
  message.sendToTarget();
3.
  Message message = Message.obtain(handler);
  //传递复杂数据类型
  Bundle data =new Bundle();
  data.putStringArray("str",new String[]{"jack","Tom","Sam"});
  message.setData(data);
  message.sendToTarget();
  Bundle bundle=msg.getData();
  System.out.println(bundle.getStringArray("str"))

2.handler

new Thread(new Runnable() {
      @Override
       public void run() {
             //1.
             handler.sendEmptyMessage(15);
             //2.在指定时间传递消息
             handler.sendEmptyMessageDelayed(3, 3000);
             //3.发送一个message
             Message message = Message.obtain();
             message.what = 1;
             handler.sendMessage(message);
       }
}).start();

你可能感兴趣的:(Handler和Message)