Android 广播指定接收者的实现方式

在 Android 中,可以通过以下几种方式实现广播只被特定接收者接收:

一、使用显式 Intent(Android 8.0+ 推荐)

// 发送广播时指定接收者类名
Intent intent = new Intent(this, MyBroadcastReceiver.class);
intent.setAction("com.example.MY_ACTION");
sendBroadcast(intent);

特点

  • 直接指定目标接收者的类
  • 只有指定的 BroadcastReceiver 能接收
  • 适用于应用内广播

二、使用权限限制

1. 自定义权限(跨应用场景)

在发送方应用的 AndroidManifest.xml 中声明权限

<permission android:name="com.example.MY_PERMISSION"
    android:protectionLevel="signature" />

发送广播时添加权限

Intent intent = new Intent("com.example.MY_ACTION");
intent.putExtra("data", "secret info");
sendBroadcast(intent, "com.example.MY_PERMISSION");

接收方应用声明使用权限

<uses-permission android:name="com.example.MY_PERMISSION" />

2. 接收方设置权限

接收方在 Manifest 中声明接收时需要的权限

<receiver android:name=".MyReceiver"
    android:permission="com.example.MY_PERMISSION">
    <intent-filter>
        <action android:name="com.example.MY_ACTION" />
    </intent-filter>
</receiver>

三、使用 LocalBroadcastManager(应用内广播)

// 发送广播
Intent intent = new Intent("com.example.LOCAL_ACTION");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

// 注册接收者
LocalBroadcastManager.getInstance(this)
    .registerReceiver(receiver, new IntentFilter("com.example.LOCAL_ACTION"));

特点

  • 只在应用内传播
  • 高效安全
  • 不需要权限声明

四、使用 setPackage() 方法限定接收应用

Intent intent = new Intent("com.example.SPECIFIC_ACTION");
intent.setPackage("com.target.app.package");
sendBroadcast(intent);

特点

  • 指定只有特定包名的应用能接收
  • 适用于定向发送给其他已知应用

五、有序广播指定最终接收者

// 发送有序广播
Intent intent = new Intent("com.example.ORDERED_ACTION");
sendOrderedBroadcast(intent, null, new FinalReceiver(), null, 
    Activity.RESULT_OK, null, null);

// 最终接收者
private static class FinalReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 只有这个接收者能处理
    }
}

六、动态注册时指定 Handler(控制接收线程)

// 在主线程处理
registerReceiver(receiver, filter, null, new Handler(Looper.getMainLooper()));

// 在工作线程处理
HandlerThread handlerThread = new HandlerThread("BroadcastThread");
handlerThread.start();
registerReceiver(receiver, filter, null, new Handler(handlerThread.getLooper()));

最佳实践建议

  1. 应用内广播优先使用 LocalBroadcastManager 或显式 Intent
  2. 跨应用通信使用自定义权限确保安全
  3. 定向广播使用 setPackage() 精确控制接收者
  4. 敏感数据应结合权限和加密传输
  5. Android 8.0+注意后台执行限制,推荐使用 JobScheduler
  6. 及时注销动态注册的接收者,避免内存泄漏

完整示例(应用内指定接收者)

// 自定义广播接收者
public class MyPrivateReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // 只有这个接收者能处理
        String data = intent.getStringExtra("data");
        Toast.makeText(context, "Received: " + data, Toast.LENGTH_SHORT).show();
    }
}

// 发送广播
Intent intent = new Intent(this, MyPrivateReceiver.class);
intent.putExtra("data", "Confidential info");
sendBroadcast(intent);

通过以上方法,可以精确控制广播的接收者,确保广播消息只被预期的组件接收。

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容