Accessing UI thread handler from a service

后端 未结 7 1548
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 11:57

I am trying some thing new on Android for which I need to access the handler of the UI thread.

I know the following:

  1. The UI thread has its own handler
7条回答
  •  悲&欢浪女
    2020-11-27 12:29

    Solution:

    1. Create a Handler with Looper from Main Thread : requestHandler
    2. Create a Handler with Looper from Main Thread: responseHandler and override handleMessage method
    3. post a Runnable task on requestHandler
    4. Inside Runnable task, call sendMessage on responseHandler
    5. This sendMessage result invocation of handleMessage in responseHandler.
    6. Get attributes from the Message and process it, update UI

    Sample code:

        /* Handler from UI Thread to send request */
    
        Handler requestHandler = new Handler(Looper.getMainLooper());
    
         /* Handler from UI Thread to process messages */
    
        final Handler responseHandler = new Handler(Looper.getMainLooper()) {
            @Override
            public void handleMessage(Message msg) {
    
                /* Processing handleMessage */
    
                Toast.makeText(MainActivity.this,
                        "Runnable completed with result:"+(String)msg.obj,
                        Toast.LENGTH_LONG)
                        .show();
            }
        };
    
        for ( int i=0; i<10; i++) {
            Runnable myRunnable = new Runnable() {
                @Override
                public void run() {
                    try {
                       /* Send an Event to UI Thread through message. 
                          Add business logic and prepare message by 
                          replacing example code */
    
                        String text = "" + (++rId);
                        Message msg = new Message();
    
                        msg.obj = text.toString();
                        responseHandler.sendMessage(msg);
                        System.out.println(text.toString());
    
                    } catch (Exception err) {
                        err.printStackTrace();
                    }
                }
            };
            requestHandler.post(myRunnable);
        }
    

提交回复
热议问题