Android BroadcastReceiver的基础学习
- 自定义广播的发送
- 黏性广播
- 自定义广播的接收
成熟是一种明亮而不刺眼的光辉,一种圆润而不腻耳的音响,一种不需要对别人察颜观色的从容,一种终于停止了向周围申诉求告的大气,一种不理会哄闹的微笑,一种洗刷了偏激的淡漠,一种无须声张的厚实,一种并不陡峭的高度。
————鲁迅《朝花夕拾》
对于广播的底层应用实现自我的接收和发送
广播的发送
activity_main.xml
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="请输入广播内容"
android:id="@+id/et_main_content"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="发送"
android:onClick="send"
/>
MainActivity
public class MainActivity extends AppCompatActivity {
private EditText et_main_content;
private Intent intent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_main_content = (EditText) findViewById(R.id.et_main_content);
intent = new Intent();
//设置广播的名字(设置Action)
intent.setAction("com.zking.risk_android20_sender.122");
}
public void send(View view) {
String content = et_main_content.getText().toString();
//携带数据
intent.putExtra("data", content);
//发送广播(无序广播)
sendBroadcast(intent);
//发送黏性广播
//sendStickyBroadcast(intent);
}
}
黏性广播在清单文件中要配置(黏性广播现在已经过时了,在这里只是提一下)
<!--添加发送黏性广播的权限-->
<uses-permission android:name="android.permission.BROADCAST_STICKY"></uses-permission>
广播的接收
MyReceived01.java
public class MyReceived01 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if("com.zking.risk_android20_sender.122".equals(intent.getAction())){
String data=intent.getStringExtra("data");
Log.i("test","01号接受者收到广播了:"+data);
}
}
}
清单文件中要配置
<receiver android:name=".MyReceived01">
<intent-filter>
<action android:name="com.zking.risk_android20_sender.122"></action>
</intent-filter>
</receiver>
MainActivity
public class MainActivity extends AppCompatActivity {
private MyReceived02 myReceived02;
private IntentFilter intentFilter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myReceived02 = new MyReceived02();
intentFilter = new IntentFilter();
intentFilter.addAction("com.zking.risk_android20_sender.122");
}
@Override
protected void onResume() {
super.onResume();
//动态注册广播
registerReceiver(myReceived02,intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
//注销动态广播
unregisterReceiver(myReceived02);
}
}
这里必须要注销,要不然会报错
MyReceived02.java
public class MyReceived02 extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
if("com.zking.risk_android20_sender.122".equals(intent.getAction())){
String data=intent.getStringExtra("data");
Log.i("test","02号接受者收到广播了:"+data);
}
}
}
静态广播与动态广播的区别在于静态广播是在清单文件中进行配置,而动态广播则是使用Java代码
静态广播退出还是会收到信息,而动态广播退出则不会接受
但是我们想动态广播退出也接受信息怎么办了,这就是我在上面提到的黏性广播的用处了