自定义广播接收不到(静态注册广播接收器)

本文详细介绍了在Android8.0及更高版本中,自定义广播接收器无法正常工作的问题及其解决方案。通过给Intent设置明确的组件信息,如包名或组件名称,可以确保应用能够接收到自定义广播。

问题:按照《第一行代码》中写的自定义广播接收器,采用静态注册的方式,在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.

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值