问题:按照《第一行代码》中写的自定义广播接收器,采用静态注册的方式,在Android8.0以及更高的版本中无法收到广播信息。需要给intent添加Component或者setPackage也行,就是需要更明确的指定处理这个intent的组件信息。
自定义广播接收器代码:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Toast.makeText(context, "received in myReceiver", Toast.LENGTH_LONG).show();
}
}
Manifest中注册信息:
<receiver
android:name=".MyBroadcastReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
发送广播代码:
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent("com.example.broadcasttest.MY_BROADCAST");
//设置包名后可以接收到自定义广播信息
//intent.setPackage(getPackageName());
//设定component后也可收到广播信息
intent.setComponent(new ComponentName(getPackageName(),
"com.example.broadcasttest.MyBroadcastReceiver"));
sendBroadcast(intent);
}
});
从源码这人两个方法的注释来看,setPackage是:
Set an explicit application package name that limits the components this Intent will resolve to. 就是指定处理这个intent的组件的包名。
setComponent是:
Explicitly set the component to handle the intent. 明确指定处理这个intent的组件。
更具体的可看官方网站说明:
https://developer.android.google.cn/about/versions/oreo/background
Beginning with Android 8.0 (API level 26), the system imposes additional restrictions on manifest-declared receivers.
If your app targets Android 8.0 or higher, you cannot use the manifest to declare a receiver for most implicit broadcasts (broadcasts that don't target your app specifically). You can still use a context-registered receiver when the user is actively using your app.
本文详细介绍了在Android8.0及更高版本中,自定义广播接收器无法正常工作的问题及其解决方案。通过给Intent设置明确的组件信息,如包名或组件名称,可以确保应用能够接收到自定义广播。
1254

被折叠的 条评论
为什么被折叠?



