Android 8.0(api27)静态广播和动态广播接收问题

Android 8.0对广播进行了限制:静态广播(应用内)需要为Intent设置setClassName(String),动态广播需要为IntentFilter设置addAction(String)同时还要为Intent设置setAction(String),并且这两个字符内容必须一样。

附代码

1.静态广播(应用内):必须设置setClassName(context, "包+类名")

//广播接收者--MyBroadcastReceiver.java
package com.example.administrator.testmvp.broadcast_receiver;

public class MyBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, intent.getAction(), Toast.LENGTH_SHORT).show();
    }
}

//注册静态广播--AndroidManifest.xml

      
         
      


// 发送静态广播-MainActivity
Intent intent = new Intent();
intent.setAction("myBroadcastReceiver");
String className = getPackageName() + ".broadcast_receiver.MyBroadcastReceiver";
intent.setClassName(MainActivity.this, className);
sendBroadcast(intent);



2.动态广播:intentFilter.addAction(String)和intent.setAction(String)字符内容必须一样


//广播接收者
package com.example.administrator.testmvp.broadcast_receiver;

public class DynamicBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context, intent.getAction(), Toast.LENGTH_SHORT).show();
    }
}

IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");
// 注册动态广播
registerReceiver(new DynamicBroadcastReceiver(), intentFilter);
// 发送动态广播
Intent intent = new Intent();
intent.setAction("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);

你可能感兴趣的:(Android 8.0(api27)静态广播和动态广播接收问题)