欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

handler消息传递机制demo

程序员文章站 2022-07-14 16:44:52
...
public class TestHandler extends AppCompatActivity {
    int num = 0;
    private TextView tv;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what % 6==0) {
                tv.setText(num + "");
            }else{
                tv.setText(num + "??????");
            }
        }
    };

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.textview_test1);
        tv = findViewById(R.id.testhandlertv);
        init();
    }

    private void init() {
        Button b = findViewById(R.id.testhandlerbutton);
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread() {
                    @SneakyThrows
                    @Override
                    public void run() {
                        while (true) {
                            Thread.sleep(1000);
                            num++;
                            handler.sendEmptyMessage(num);
                        }
                    }
                }.start();
            }
        });
    }
}
相关标签: android