Accessing UI thread handler from a service

后端 未结 7 1497
被撕碎了的回忆
被撕碎了的回忆 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

    At the moment I prefer using event bus library such as Otto for this kind of problem. Just subscribe the desired components (activity):

    protected void onResume() {
        super.onResume();
        bus.register(this);
    }
    

    Then provide a callback method:

    public void onTimeLeftEvent(TimeLeftEvent ev) {
        // process event..
    }
    

    and then when your service execute a statement like this:

    bus.post(new TimeLeftEvent(340));
    

    That POJO will be passed to your above activity and all other subscribing components. Simple and elegant.

    0 讨论(0)
  • 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);
        }
    
    0 讨论(0)
  • 2020-11-27 12:30

    You can get values through broadcast receiver......as follows, First create your own IntentFilter as,

    Intent intentFilter=new IntentFilter();
    intentFilter.addAction("YOUR_INTENT_FILTER");
    

    Then create inner class BroadcastReceiver as,

        private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        /** Receives the broadcast that has been fired */
        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction()=="YOUR_INTENT_FILTER"){
               //HERE YOU WILL GET VALUES FROM BROADCAST THROUGH INTENT EDIT YOUR TEXTVIEW///////////
               String receivedValue=intent.getStringExtra("KEY");
            }
        }
    };
    

    Now Register your Broadcast receiver in onResume() as,

    registerReceiver(broadcastReceiver, intentFilter);
    

    And finally Unregister BroadcastReceiver in onDestroy() as,

    unregisterReceiver(broadcastReceiver);
    

    Now the most important part...You need to fire the broadcast from wherever you need to send values..... so do as,

    Intent i=new Intent();
    i.setAction("YOUR_INTENT_FILTER");
    i.putExtra("KEY", "YOUR_VALUE");
    sendBroadcast(i);
    

    ....cheers :)

    0 讨论(0)
  • 2020-11-27 12:40

    I suggest trying following code:

        new Handler(Looper.getMainLooper()).post(() -> {
    
            //UI THREAD CODE HERE
    
    
    
        });
    
    0 讨论(0)
  • 2020-11-27 12:43

    Create a Messenger object attached to your Handler and pass that Messenger to the Service (e.g., in an Intent extra for startService()). The Service can then send a Message to the Handler via the Messenger. Here is a sample application demonstrating this.

    0 讨论(0)
  • 2020-11-27 12:44

    This snippet of code constructs a Handler associated with the main (UI) thread:

    Handler handler = new Handler(Looper.getMainLooper());
    

    You can then post stuff for execution in the main (UI) thread like so:

    handler.post(runnable_to_call_from_main_thread);
    

    If the handler itself is created from the main (UI) thread the argument can be omitted for brevity:

    Handler handler = new Handler();
    

    The Android Dev Guide on processes and threads has more information.

    0 讨论(0)
提交回复
热议问题