android 中自定义广播的使用broardcast
来源:互联网 发布:云计算峰会的会议定位 编辑:程序博客网 时间:2024/06/03 11:17
在android系统中,有很多系统级的广播,如网络连接变化、锁屏、充电状态、日期时间变更等等,但有时候只用系统的广播很难满足我们的要求,所以需要用到自定义广播。
若要实现自定义广播,大概分为三个步骤: 1.注册广播 2.发送广播 3.接收广播 而注册广播也有两种方式,一种为动态注册,另一种为静态注册,静态注册需要在manifest文件中去生命广播的接收者,而动态注册则需要代码中去生命广播接收者
首先看静态注册:
我们要new出一个类继承自BroadcastReceiver,并实现其onReceive方法:
public class TestReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Toast.makeText(context , "receiver" , Toast.LENGTH_SHORT).show(); }}
然后在AndroidManifest文件的<application>标签中去静态的注册该广播接收者:
<receiver android:name=".TestReceiver"> <intent-filter> <action android:name="test"/> </intent-filter></receiver>
注意需要在<intent-filter>标签中生命该receiver的action,且action的name不要与系统的action重名,当我们发出广播时,会根据action去寻找响应该广播的receiver。
接下来,我们在某个activity中发出广播:
private void sendBroadcast(){ Intent intent = new Intent(); intent.setAction("test"); sendBroadcast(intent);}这样,就完成了静态注册广播并发送和接收的整个过程。接下来是动态注册,其实跟静态注册是类似的,只不过静态注册的情况下,不管应用有没有用到这个广播,该广播都会注册,而动态注册只会在需要用到的时候去注册。动态注册广播的代码:private void registerReceiver(){ mReceiver = new TestReceiver(); IntentFilter filter = new IntentFilter(); filter.addAction("test"); registerReceiver(mReceiver , filter);}发出广播的代码:private void sendBroadcast(){ Intent intent = new Intent(); intent.setAction("test"); sendBroadcast(intent);}另:如该广播已经没有地方用到,可以将其解绑,代码如下:private void unRegisterReceiver(){ unregisterReceiver(mReceiver);}
0 0
- android 中自定义广播的使用broardcast
- Android中广播的使用
- 【Android】Android中广播的基本使用
- Android中广播的简单使用
- android 广播的使用
- android 广播的使用
- android 广播的使用
- android 广播的使用
- android 广播的使用
- android 广播的使用
- Android的广播使用
- android 广播的使用
- Android广播的使用
- android 广播的使用
- Android广播的使用
- Android中广播BroadCastReceiver使用
- Android中广播的使用(动态、静态注册的区别,有序无序广播的使用)
- Android进阶之路 - BroadcaseReceiver(自定义广播、有序广播、无序广播、广播拦截、动态注册、静态注册)的详细使用方式
- No enclosing instance of type E is accessible. Must qualify the allocation with an enclosing instanc
- 【水题】高精度加法
- Hibernate 注解方式 save后获取不到对象id一种情况
- http(3)详解------Web的结构组件
- 关于在Java学习中遇到的浮躁
- android 中自定义广播的使用broardcast
- CSS总结(1)
- 解决Android中LayoutParam宽高的单位设置问题
- Android API Guides 阅读笔记(6)----Task and Back Stack
- VS2012启用SQLite的Data Provider
- leetCode(52):Add Binary
- Fragment向Fragment传值(第一种)
- linux常用命令----文本的统计
- HDU 4175 多时段多课最小能量消耗问题-dp-(数塔模型)