Basic concepts of Android (40) Handler



In Android development, you will inevitably encounter the scene of main thread and new UI, thread switching, in which Handler is a general, so it is necessary to understand him.

1, The basic concept of graphical Handler

What is the Handler? The Handler is a set of mechanisms provided by Android to follow the new UI, as well as a set of message processing mechanisms. You can send or process messages through it. Let's see the figure below.


2, Why use Handler

Why can Android design only through Handler mechanism and new UI? The most fundamental purpose is to solve the problem of multithreading concurrency. Only the main thread can update the UI
Imagine multithreading to update the ui without the shackle mechanism, which will cause confusion with the new interface. If you shackle the new ui operation, it will cause performance degradation, and the Handler appears

3, How to use the Handler

  • Main thread declares Handler instance
private Handler mHandler = new Handler(new Handler.Callback() {
        /**
         * @param message callback Used to get the message sent by handler,
         * @return  If it returns true, it will go back successfully without passing down the old one, that is, the following handleMessage method will not be executed to intercept
         */
        @Override
        public boolean handleMessage(Message message) {
            return false;
        }
    }){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 0:
                    //Here you can perform UI operations
                    //String cast msg.obj
                    String str = (String) msg.obj;
                    mTvShow.setText(str);
                    break;
                default:
                    break;
            }
        }
    };

  • Message sent by child thread
mTvShow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(2000);//Simulate network operation
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        //Create a message to set the value of what field to 1, mainly to distinguish different messages
                        //Set the content of message.obj and call the message object of Handler
                        String str = "Nice to Meet You";
                        Message msg = new Message();//Create message object Message msg = mHandler.obtainMessage(), which can also be reused;
                        msg.what = 0;//Message marking
                        msg.arg1=2;//If the data is easy to carry, arg1 and arg2 are preferred, which saves more memory than Bundle.
                        msg.arg2=3;   //Store shaping data
                        //msg.obj = str;//msg.obj = xxx can pass an object
                        Bundle bundle=new Bundle();
                        bundle.putString("dd","adfasd");
                        bundle.putInt("love",5);
                        msg.setData(bundle);
                        msg.obj=bundle;   //Used to store any Object of type Object
                        mHandler.sendMessage(msg);//Send msg to UI thread to update UI

                        /**
                         * mHandler.sendEmptyMessage(int);Publish an empty message
                         * mHandler.sendMessage(msg);Allows you to arrange Message objects with data to queue for updating.
                         * mHandler.sendMessageAtTime(Message,long);
                         * mHandler.sendMessageDelayed(Message,long);
                         * sendEmptyMessageAtTime(int what, long uptimeMillis); //Send empty message regularly
                         * sendEmptyMessageDelayed(int what, long delayMillis); //Delay sending empty message
                         * sendMessageAtFrontOfQueue(Message msg); //Handle messages first (use caution)
                         */
                    }
                }).start();
            }
        });


Tags: Android network

Posted on Mon, 30 Mar 2020 22:40:18 -0700 by zeberdeee