Handler使用
2021-05-29 本文已影响0人
因为我的心
一、前言:
Handler是android为我们封装的一套消息处理的机制,也是一套子线程用来更新UI的机制
1、Java使用:
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
private MyRunnable mr = new MyRunnable();
private int index = 0;
class MyRunnable implements Runnable {
public void run() {
index++;
Log.d("8888","====index: "+index);
mHandler.postDelayed(mr, 1000);
}
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler.postDelayed(mr, 1000);
}
}
//移除handler
mHandler.removeCallbacks(mr )
2、Kotlin使用:
var handler: Handler = Handler()
//执行
handler.postDelayed(this, 100)
var runnable: Runnable = object : Runnable {
override fun run() {
//操作事件
.........
//延迟1秒
handler.postDelayed(this, 1000)
}
}
//移除handler
handler.removeCallbacks(runnable)