In-depth analysis of Android BroadcastReceiver (7)

Article Directory

    • In-depth Analysis of Android Broadcast Receiver (7)
      • 1. Advanced application scenarios
        • 1.1 Example: Dynamic Permission Request
        • 1.2 Example: In-app notification update
      • 2. Security and performance optimization
        • 2.1Example: Setting Permissions to Prevent Broadcast Attacks
        • 2.2 Example: Using the Local Broadcast Manager
        • 2.3 Example: Registering and unregistering a broadcast receiver in the life cycle
      • 3. Sum up

In-depth Analysis of Android Broadcast Receiver (7)

1. Advanced application scenarios

  1. Dynamic permission request

In Android 6.0 (API 23) and above, applications need to request permissions at runtime. BroadcastReceiver can be used to listen for permission changes and take appropriate action when permission is granted or denied.

1.1 Example: Dynamic Permission Request

Request Permission:

ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, REQUEST_CAMERA_PERMISSION); 

Result of processing permission request:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // permission granted,Send broadcast
            Intent intent = new Intent("com.example.PERMISSION_GRANTED");
            sendBroadcast(intent);
        } else {
            // Permission denied
            Toast.makeText(this, "Camera permission denied", Toast.LENGTH_SHORT).show();
        }
    }
} 

Broadcast receivers that listen for permission changes:

public class PermissionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        if ("com.example.PERMISSION_GRANTED".equals(intent.getAction())) {
            // Handle operations after permissions are granted
            Toast.makeText(context, "Camera permission granted", Toast.LENGTH_SHORT).show();
        }
    }
}

// exist Manifest Declare the receiver in the file
<receiver android:name=".PermissionReceiver">
    <intent-filter>
        <action android:name="com.example.PERMISSION_GRANTED"/>
    </intent-filter>
</receiver> 
  1. In-app update notification

The notification update in the application can be realized through the broadcast mechanism. For example, if a module updates data, it needs to notify other modules to perform corresponding operations.

1.2 Example: In-app notification update

Send broadcast notification:

Intent intent = new Intent("com.example.DATA_UPDATED");
intent.putExtra("data", "New data available");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent); 

Receive broadcast notification:

@Override
protected void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter("com.example.DATA_UPDATED");
    LocalBroadcastManager.getInstance(this).registerReceiver(dataUpdateReceiver, filter);
}

@Override
protected void onStop() {
    super.onStop();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(dataUpdateReceiver);
}

private final BroadcastReceiver dataUpdateReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String data = intent.getStringExtra("data");
        // Handle data updates
        Toast.makeText(context, "Data updated: " + data, Toast.LENGTH_SHORT).show();
    }
}; 

2. Security and performance optimization

  1. Avoid broadcast attacks

Public broadcasting may be used by malicious applications to broadcast attacks, resulting in security problems. Setting the appropriate permissions for the broadcast receiver can be an effective way to prevent such attacks.

2.1Example: Setting Permissions to Prevent Broadcast Attacks

Set permissions when sending a broadcast:

Intent intent = new Intent("com.example.SECURE_ACTION");
sendBroadcast(intent, "com.example.MY_PERMISSION"); 

Receiver Asserts Permissions:

<receiver android:name=".SecureReceiver" android:permission="com.example.MY_PERMISSION">
    <intent-filter>
        <action android:name="com.example.SECURE_ACTION"/>
    </intent-filter>
</receiver> 
  1. Using the Local Broadcast Manager

Broadcast communication is performed LocalBroadcastManager only within the application, which is more secure and efficient.

2.2 Example: Using the Local Broadcast Manager

Send local broadcast:

LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);
Intent intent = new Intent("com.example.LOCAL_EVENT");
localBroadcastManager.sendBroadcast(intent); 

Receive local broadcast:

@Override
protected void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter("com.example.LOCAL_EVENT");
    LocalBroadcastManager.getInstance(this).registerReceiver(localEventReceiver, filter);
}

@Override
protected void onStop() {
    super.onStop();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(localEventReceiver);
}

private final BroadcastReceiver localEventReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle local events
        Toast.makeText(context, "Local event received", Toast.LENGTH_SHORT).show();
    }
}; 
  1. Rational Life Cycle Management

Reasonably register and unregister the broadcast receiver during the life cycle of the component to avoid memory leaks and waste of resources.

2.3 Example: Registering and unregistering a broadcast receiver in the life cycle
@Override
protected void onStart() {
    super.onStart();
    IntentFilter filter = new IntentFilter("com.example.SOME_ACTION");
    registerReceiver(someReceiver, filter);
}

@Override
protected void onStop() {
    super.onStop();
    unregisterReceiver(someReceiver);
}

private final BroadcastReceiver someReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        // Handle received broadcasts
    }
}; 

3. Sum up

Broadcast mechanism is a very flexible and powerful component communication method in Android, which is suitable for a variety of application scenarios. Diversified communication needs can be achieved through system broadcast, custom broadcast, ordered broadcast, and local broadcast. In practical applications, developers need to choose the appropriate broadcast mechanism according to specific requirements, and improve the performance and security of the application through optimization strategies.

  • Dynamic permission request: Use the broadcast mechanism to monitor the change of permission and handle the operation after the permission is granted or denied in time.
  • In-app update notification: Implement data update notification between modules through broadcasting to keep loose coupling between components.
  • Security optimization: Avoid broadcast attacks by setting permissions and using LocalBroadcast Manager to improve the security of the broadcast.
  • Performance optimization Manage the lifecycle of the broadcast receiver to avoid memory leaks and waste of resources.