How to pass data from BroadcastReceiver to Activity without in onCreate()

后端 未结 3 1803
陌清茗
陌清茗 2021-01-21 01:56

I have a serious issue about passing data from BroadcastReceiver to an Activity. Let see my issue carefully. I have a class PhoneStateReceiver ex

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 02:54

    Simple without any third party libs.

    Make sure BroadcastReceiver must be registered and also unregistered on OnPause().

    You have to do two thing

    Register a receiver in you activity like below.

    public class MainActivity extends Activity {
    
        Context context;
        BroadcastReceiver updateUIReciver;
    
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            context = this;
    
            IntentFilter filter = new IntentFilter();
            filter.addAction("service.to.activity.transfer");
            updateUIReciver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    //UI update here
                    if (intent != null)
                        Toast.makeText(context, intent.getStringExtra("number").toString(), Toast.LENGTH_LONG).show();
                }
            };
            registerReceiver(updateUIReciver, filter);
        }
    }
    

    Now in you service

    public class PhoneStateReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                System.out.println("Receiver start");
                String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
                String incomingNumber = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    Intent local = new Intent();
                    local.setAction("service.to.activity.transfer");
                    local.putExtra("number", incomingNumber);
                    context.sendBroadcast(local);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    

提交回复
热议问题