Android send data from main UI thread to another thread

后端 未结 3 1557
忘了有多久
忘了有多久 2021-02-10 02:44

I need to send some data from the main thread to another thread. I\'ve already read a lot of materials on threads, asynctasks and handlers but maybe they created some confusion

3条回答
  •  执念已碎
    2021-02-10 03:12

    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 background thread to send values..... so do as,

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

    ....cheers :)

提交回复
热议问题