首先,咱定义一个handle1在主线程:(记住添加一个Button)
Handler handler1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initEvent(); handler1= new Handler(); handler1.sendEmptyMessage(1000); }
接着开辟一个子线程,再接受一个handleMessage:
new Thread(){ @Override public void run() { Looper.prepare(); super.run(); handler1 = new Handler(){ @Override public void handleMessage(@NonNull Message msg) { super.handleMessage(msg); Log.d("TAP","从UI中传来的handler值是:"+msg.what); } }; Looper.loop(); //相当于产生了一个while(true){} } }.start();
我们设置,当点击按钮的时候,把主线程的what传过去:
ui.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { handler1.sendEmptyMessage(1000); } });