Day 12 BroadCastReceiver broadcast

BroadCastReceiver

1, BroadCastReceiver introduction:

  • BroadCastReceiver broadcast receiver, one of the four components of Android
  • Three elements of Broadcasting:
    (1) Broadcast sender: send broadcast
    (2) Broadcast receiver (FM): used to receive broadcast
    (3) Things to deal with: deal with broadcast related information. Intent has a graph object
  • Usage scenario of broadcast:
    (1) Data transfer between multiple components under the same APP (data transfer between activities / fragments / services)
    (2) Data transfer between two apps
  • Skill points:
    (1) Custom broadcast recipients
    (2) Use the broadcast receiver to intercept calls and SMS and change the power of the system

2, How to realize broadcasting

Step 1: broadcast receiver
(1) The custom class inherits BroadcastReceiver and overrides onReceive method
(2) Registration broadcast (all four components of Android need to be registered)

  • Static registration: in manifest file
  • Dynamic registration: register in code (register and unregister)

Step 2: Broadcast sender: sendBroadcast(Intent intent object)

The difference between static registration and dynamic registration: if Activity is the recipient:
Dynamic registration:
(1) The broadcast will end with the end of the life cycle of the Activity;
(2) Free control of registration and cancellation, with great flexibility
Static registration:
(1) The broadcast will not end with the end of the life cycle of the Activity. It always exists. Even if the application is closed, it will be awakened to accept the broadcast
(2) Global broadcast

3, Code case:

(1) The custom broadcast receiver class inherits BroadCastReceiver and overrides onReceiver method

 public class MyReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
        //TODO 1: get action
        String action = intent.getAction();
        if("android.bawei.action.customer".equals(action)){
            Bundle bundle = intent.getExtras();
            int msg=bundle.getInt("msg");
            Log.i("radio broadcast", "Received a broadcast: "+msg);

        }
    }
}

(2) Registration broadcast mode 1: static registration of list file

 <!--radio-->
        <receiver android:name=".MyReceiver">
            <!--frequency modulation-->
            <intent-filter>
                <action android:name="android.bawei.action.customer" />
            </intent-filter>
        </receiver>

(3) Registration broadcast mode 2: dynamic registration
onCreate(): register the broadcast and call the registerReceiver() method of the Context
onDestory(): deregister and call unregisterReceiver() method of Context

public class MainActivity extends AppCompatActivity {
    private MyReceiver receiver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        receiver=new MyReceiver();
        regeister();//Register broadcast
    }
    private void regeister() {
        //TODO 1: create filter
        IntentFilter intentFilter=new IntentFilter();
        //TODO 2: frequency modulation:
        intentFilter.addAction("android.bawei.action.customer");
        //TODO 3: Register: register this Activity
        registerReceiver(receiver,intentFilter);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);//Deregister
    }
}

(4) Sender: sendroad (Intent object)

 //Button click event
    public void customer(View view) {
        Intent intent=new Intent();
        intent.setAction("android.bawei.action.customer");
        Bundle bundle=new Bundle();
        bundle.putString("msg","Send broadcast");
        intent.putExtras(bundle);
        sendBroadcast(intent);
    }

4, Classification of Broadcasting:

1. Unordered broadcast: sendBroadcast ()

2. Orderly broadcast: sendOrderBroadcast ()

When an ordered broadcast is sent, the receiver with higher priority receives the broadcast first. You can call abortBroadCast() to interrupt the broadcast and prevent others from accepting the broadcast.

3. Sticky broadcast: sendsticky broadcast ()

Store the messages sent by the previous broadcast sender, and ordinary broadcasts cannot accept the messages sent before

5, Get system broadcast: dynamic registration

More broadcasts: https://blog.csdn.net/cc_want/article/details/82344899

1. Incoming call monitoring

(1) Add permissions:

android.permission.READ_PHONE_STATE

(2) Registered broadcasting (dynamic broadcasting is used here)

		musicRecevicer = new MusicRecevicer();
        IntentFilter intentFilter = new IntentFilter();
     	intentFilter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);//Incoming call monitoring       
        getActivity().registerReceiver(musicRecevicer,intentFilter);

(3) Create and accept broadcast objects

class MusicRecevicer extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
           if(TelephonyManager.ACTION_PHONE_STATE_CHANGED.equals(intent.getAction())){//Call
                TelephonyManager telephonyManager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                telephonyManager.listen(new PhoneStateListener(){
                    @Override
                    public void onCallStateChanged(int state, String phoneNumber) {
                        super.onCallStateChanged(state, phoneNumber);
                        switch (state){
                            case TelephonyManager.CALL_STATE_RINGING://Call
                                musicBinder.pause();
                                break;

                            case TelephonyManager.CALL_STATE_IDLE://Hang up
                                musicBinder.start();
                                break;

                            case TelephonyManager.CALL_STATE_OFFHOOK://fairy tale
                                musicBinder.pause();
                                break;

                        }
                    }
                },PhoneStateListener.LISTEN_CALL_STATE);

            }
        }
    }

(4) Log off broadcast object

@Override
    public void onDestroyView() {
        super.onDestroyView();
        if(musicRecevicer != null){
            getActivity().unregisterReceiver(musicRecevicer);
        }
    }

2. Network status monitoring

(1) Add permissions:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

(2) Registered broadcasting (dynamic broadcasting is used here)

Tags: Android

Posted on Fri, 22 Oct 2021 20:32:52 -0400 by Cochise