本节新建一个项目
day09_MyBroadcastReceiver
,记为项目一
Android 8.0
及以上 在xml
中注册的广播,在接收的时候收到了额外的限制,如果你的app目标等级是26及以上,将无法接收到xml注册的广播,这是google 为了app注册的静态广播导致耗电加的限制。
既然不能静态注册,那么有啥可用的注册方法呢?
一、无需注册就能发送定向发送广播
定向发送广播,广播接收器无需注册【静态注册和动态注册都不需要】,必须指定本包的的广播接收器,无法向其他应用发送广播
1、创建广播接收器
MyBroadcastReceiver.java
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"自定义广播接收器已经接收到消息", Toast.LENGTH_LONG).show();
}
}
2、主布局修改
没啥好说的,就一个按钮
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送广播"
android:id="@+id/button"/>
</LinearLayout>
3、主活动
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main)