android study notes the handler message handling mechanisms 1

In andorid in a process there are at least a thread, in general, there is a main thread (also UI thread); and a plurality of sub-threads (also called Worker threads).
There are a rule in the android: For security reasons, the sub-thread can not dynamically change the attribute values of the components in the main thread.
But in order to perform some time-consuming operation, they will often put the child thread, the main thread is finished to update the UI, so there is a handler message handling mechanism.
handler is equivalent to a transfer station, by the child thread sendMessage () method and the like, sends a message to an object handler, processing handler for related messages sent in accordance with the main thread, so as to achieve the main thread Update child thread.
The following write Demo:
1. layout, a TextView and a Button, Button click realize effect a change in the value of the TextView child thread. As shown
Here Insert Picture Description
in 2.MainActivity (Note that the packet is to be imported Handler OS)

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TextView textView= (TextView) findViewById(R.id.text);
        Button button= (Button) findViewById(R.id.button);
        final Handler handler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what==123){
                    textView.setText("sb");
                }
            }
        };
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        handler.sendEmptyMessage(123);
                    }
                }).start();
            }
        });
    }
Published 28 original articles · won praise 15 · views 7840

Guess you like

Origin blog.csdn.net/qq_34423913/article/details/104525561