Android BroadcastReceiver uses

Broadcasts in Android are mainly divided into two types, standard broadcasts and ordered broadcasts.

  • Standard broadcast: It is a completely asynchronous broadcast. After the broadcast is sent, all broadcast receivers will receive the broadcast message almost at the same time, and there is no order at all. This kind of broadcast will be more efficient and cannot be truncated
    insert image description here
  • Ordered broadcast: It is a synchronously executed broadcast. After the broadcast is sent, only one broadcast receiver can receive the broadcast message at the same time. After the logic in the broadcast receiver is executed, the broadcast will continue transfer. Therefore, the broadcast receivers at this time are in order. The broadcast receiver with high priority can receive the broadcast message first, and the previous broadcast receiver can also intercept the broadcast being delivered, so that the latter broadcast receiver cannot receive the broadcast message. A broadcast message has been received.
    insert image description here

Broadcast registration is divided into static registration and dynamic registration

  • Static registration: Configure through AndroidManifest.xml to realize the
    static broadcast of the broadcast, and the broadcast can be received when the application is not started
  	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 	<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        
        <receiver android:name=".NetWorkReceiverTest">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
        
   </application>
  • Dynamic registration: It is to register in the code that
    the broadcast of dynamic registration can freely control the registration and cancellation, which has great advantages in flexibility. But there is a disadvantage, that is, the broadcast must be received after the program is started.
       var intentFilter = IntentFilter()
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE")
        var netWorkReceiverTest = NetWorkReceiverTest()
        registerReceiver(netWorkReceiverTest, intentFilter)

Guess you like

Origin blog.csdn.net/u013290250/article/details/104020451