课程背景:
BroadcastReceiver 是Android 四大基本组件之一,用于接收广播信息,如:开屏、锁屏、短信等等,在实际工作中用途非常广泛
核心内容:
1. 动态注册和注销 BroadcastReceiver
使用 BroadcastReceiver
新建Brodercast Receiver文件:
在Receiver自动生成的onReceive方法中自定义接收到信息后的处理代码:
@Override public void onReceive(Context context, Intent intent) { System.out.println("接收到了消息,消息的内容是: "+intent.getStringExtra("data")); }
Aty中发送消息给Receiver,还可以在Intent中方便地传数据:
Intent i = new Intent(this, MyReceiver.class); i.putExtra("data", "lanyunwork"); sendBroadcast(i);
动态注册和注销 BroadcastReceiver
先删去AndroidManifest.xml中自动配置的标签,
动态注册必须要用隐式Intent,为了方便可将MyReceiver的包名定义成常量:
然后在Activity中注册/注销
private MyReceiver receiver = null; //注册——传隐式Intent registerReceiver(receiver, new IntentFilter(MyReceiver.ACTION)); //注销 unregisterReceiver(receiver);
时间: 2024-10-12 23:39:26