在 Android 12 上,广播接收器的 onReceive 方法中,intent.getExtras() 方法返回的始终是 null。这是由于 Android 12 中对隐式广播的安全性进行了增强导致的。
为了解决此问题,可以通过添加 intent 的 flags 属性来显式声明要接收的广播。例如,如果要接收 ACTION_SCREEN_ON 意图,则可以像下面这样声明:
Intent intent = new Intent(Intent.ACTION_SCREEN_ON);
intent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
此外,还需要在 AndroidManifest.xml 文件中声明接收器,并添加一个 intent-filter,如下所示:
最后,在广播接收器的 onReceive 方法中,可以通过 bundle 参数来获取传递的数据,例如:
@Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
String message = bundle.getString("message");
Log.d(TAG, "Received message: " + message);
}
}