BroadcastReceiver in Android

What is BroadcastReceiver?

Android app s are designed for sending/subscribing by sending broadcasts and receiving broadcasts sent by the system or other apps.These broadcasts are sent when important events occur.For example, the Android system sends broadcasts when various system events occur, such as when the phone starts or when the phone starts charging.Applications can also send custom broadcasts, such as notifying other applications of something they might be interested in, such as new content being downloaded.

System broadcasts are sent when system events occur, such as when a mobile phone enters or exits the developer option, and can be received by anyone who subscribes to the system broadcasts.

Broadcasting itself is wrapped in an Intent and has a unique identity (for example, android.intent.action.AIRPLANE_MODE).This Intent object also contains some other information. In its field, the intent contains a boolean field to indicate whether the flight mode is on or off.

What can BroadcastReceiver do?

  1. Important broadcasts sent by the receiving system (network changes, power on, charging)
  2. The means by which app s communicate and activate with each other
  3. Means of communication between app internal groups

What are the categories of BroadcastReceiver?

Distinguished from different latitudes, they may be classified into different categories.

  1. System broadcast/non-system broadcast
  2. Global/Local Broadcasting
  3. Random/Ordered/Sticky

How does BroadcastReceiver work?

1. Register Broadcast

1.1 Static Registered Broadcast

<receiver android:name=".MyBroadcastReceiver"  android:exported="true">
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED"/>
        <action android:name="android.intent.action.INPUT_METHOD_CHANGED" />
    </intent-filter>
</receiver>

1.2 Dynamic Registration Broadcasting

val br: BroadcastReceiver = MyBroadcastReceiver()
val filter = IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION).apply {
    addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED)
}
registerReceiver(br, filter)

2. Send a broadcast

Intent().also { intent ->
    intent.setAction("com.example.broadcast.MY_NOTIFICATION")
    intent.putExtra("data", "Notice me senpai!")
    sendBroadcast(intent)
}
sendBroadcast(Intent("com.example.NOTIFY"), Manifest.permission.SEND_SMS)
<uses-permission android:name="android.permission.SEND_SMS"/>

3. Receive broadcasts

private const val TAG = "MyBroadcastReceiver"

class MyBroadcastReceiver : BroadcastReceiver() {

    override fun onReceive(context: Context, intent: Intent) {
        StringBuilder().apply {
            append("Action: ${intent.action}\n")
            append("URI: ${intent.toUri(Intent.URI_INTENT_SCHEME)}\n")
            toString().also { log ->
                Log.d(TAG, log)
                Toast.makeText(context, log, Toast.LENGTH_LONG).show()
            }
        }
    }
}
<receiver android:name=".MyBroadcastReceiver"
          android:permission="android.permission.SEND_SMS">
    <intent-filter>
        <action android:name="android.intent.action.AIRPLANE_MODE"/>
    </intent-filter>
</receiver>
var filter = IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED)
registerReceiver(receiver, filter, Manifest.permission.SEND_SMS, null )
<uses-permission android:name="android.permission.SEND_SMS"/>

What are the differences between different versions of API s for BroadcastReceiver?

Android 9

Starting with Android 9(API level 28), NETWORK_STATE_CHANGED_ACTION broadcasts do not carry users'geographic location information or personal identity data.In addition, when your app runs on an Android 9 or higher phone, the system's wifi broadcasts will not carry SSIDs, BSSIDs, connection information or scan results.To get this information, you need to replace it with getConnectionInfo().

Android 8

Starting with Android 8(API level 27), further restrictions on static broadcasts have been tightened. Many broadcasts are registered statically and cannot be received, but you can receive these broadcasts dynamically.

Android 7

Starting with Android 7(API level 24), the system will no longer send broadcasts of ACTION_NEW_PICTURE,ACTION_NEW_VIDEO.At the same time, from 7.0 onwards, app wants to accept CONNECTIVITY_ACTION broadcasts. It needs to register broadcasts dynamically, but it is not possible to register by static broadcasts.

How does BroadcastReceiver work by sending and receiving broadcasts?

Look at the picture, draw a picture

How does BroadcastReceiver trigger ANR?

It is well known that broadcasting causes ANRs because the sender sends the broadcast to AMS, then AMS looks for anyone to register, finds it, and lets it execute. AMS starts time-consuming statistics for ANRs before execution begins. If an app process already exists at this time, this message is added to the message queue, waiting for dispatch, and finally execution is completed.If app does not exist, AMS will pull our process, and then our app will execute this message, so if we are pulled by the broadcast, our startup duration will also be counted to the ANR time range. At the beginning of this year, I spent a month to compile a set of knowledge system. If you have the idea of in-depth and systematic learning, you can click Portal I will send all the information I have collected and sorted to you to help you progress faster.

Tags: Mobile Android network

Posted on Sun, 10 Nov 2019 21:51:04 -0500 by vaan