前言:Android自定义广播的文章在各个地方都有很多,但是很多的都是针对8.0以下的,是靠静态注册的方法进行的注册,但是8.0就无效了,而且系统也不报错,但接收者里的方法就是执行不出来,相信很多的初学者都有被此烦恼过吧。
一、自定义广播接收者
public class MyBroadcastReceiverextends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context,"这是一个自定义广播的接收者",Toast.LENGTH_SHORT).show();
}
}
二、动态注册广播的方法(使用Activity调用)
private IntentFilter intentFilter;
private MyBroadcastReceiver myBroadcastReceiver;
private void receiverTask() {
intentFilter =new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");//为自定义的广播添加一个行为,需要注册什么广播就添加什么行为
myBroadcastReceiver =new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver, intentFilter);//register 注册 receiver 接收者 注册一个动态广播
}
三、发送广播(可以使用按钮的点击事件发送广播)
Intent intent =new Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
四、取消注册动态广播(在该Activity被销毁时)
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
}
附:全部代码
1.Activity代码
public class TaskTwoActivityextends AppCompatActivity {
private ButtonmTaskTwo;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task_two);
receiverTask();
initView();
}
private void initView() {
mTaskTwo = findViewById(R.id.task_two);
mTaskTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =new Intent("com.example.broadcasttest.MY_BROADCAST");
sendBroadcast(intent);
}
});
}
private IntentFilterintentFilter;
private MyBroadcastReceivermyBroadcastReceiver;
private void receiverTask() {
intentFilter =new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.MY_BROADCAST");/
myBroadcastReceiver =new MyBroadcastReceiver();
registerReceiver(myBroadcastReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(myBroadcastReceiver);
}
}
2.xml代码
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BroadcastReceiverTaskTwo.TaskTwoActivity">
android:id="@+id/task_two"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="开启一条自定义的广播" />
</android.support.constraint.ConstraintLayout>
网友评论