Android的广播Receiver动态注册和静态注册示例
程序员文章站
2023-12-18 09:09:04
广播接收器注册一共有两种形式 : 静态注册和动态注册.
两者及其接收广播的区别:
1.动态注册的广播 永远要快于 静态注册的广播,不管静态注册的优先级设置的多高,不管动...
广播接收器注册一共有两种形式 : 静态注册和动态注册.
两者及其接收广播的区别:
1.动态注册的广播 永远要快于 静态注册的广播,不管静态注册的优先级设置的多高,不管动态注册的优先级有多低。
2.动态注册广播不是 常驻型广播 ,也就是说广播跟随activity的生命周期。注意: 在activity结束前,移除广播接收器。
静态注册是常驻型 ,也就是说当应用程序关闭后,如果有信息广播来,程序也会被系统调用自动运行。
3.在同一个优先级下,谁先启动的快,谁将先接收到广播。
下面这个demo,界面如下,注册两个动态接收器(接收自定义广播和系统广播)和注册静态广播(接收自定义静态和广播、手机usb的插拔事件、接收短信并读取短信息)
工程目录如下:注意看代码中的注释
xml布局文件(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?> <linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <button android:id="@+id/send_static" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送自定义静态注册广播"/> <button android:id="@+id/send_dynamic" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送自定义动态注册广播"/> <button android:id="@+id/send_system" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="发送系统动态注册广播"/> </linearlayout>
manifest.xml如下,这里面定义的权限信息和注册的广播
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.nii.receiver" > <!--监听短信息--> <uses-permission android:name="android.permission.receive_sms" /> <uses-permission android:name="android.permission.read_sms" /> <application android:allowbackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsrtl="true" android:theme="@style/apptheme" > <activity android:name=".mainactivity" > <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter> </activity> <!-- 注册自定义静态广播接收器 --> <receiver android:name=".staticreceiver"> <intent-filter> <action android:name="com.byread.static" /> </intent-filter> </receiver> <!-- 注册系统静态广播接收器 --> <receiver android:name=".systemreceiver"> <intent-filter> <action android:name="android.intent.action.battery_low" /> <action android:name="android.provider.telephony.sms_received"/> <action android:name="android.hardware.usb.action.usb_state"/> </intent-filter> </receiver> </application> </manifest>
mainactivity.java
package com.nii.receiver; import android.manifest; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.content.intentfilter; import android.support.v7.app.appcompatactivity; import android.os.bundle; import android.util.log; import android.view.view; import android.widget.button; import android.widget.toast; import com.nii.receiver.type.requestpermissiontype; import com.nii.receiver.util.permissionutil; public class mainactivity extends appcompatactivity { /** * 发送静态广播按钮 */ private button sendstaticbtn; /** * 发送动态广播按钮 */ private button senddynamicbtn; /** * 发送系统广播按钮 */ private button sendsystembtn; /** * 静态action */ private static final string staticaction = "com.byread.static"; /** * 动态action */ private static final string dynamicaction = "com.byread.dynamic"; /** * usb设备连接 */ private static final string systemaction = intent.action_power_connected; private context mcontext; @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); setcontentview(r.layout.activity_main); this.mcontext = this; sendstaticbtn = (button) findviewbyid(r.id.send_static); senddynamicbtn = (button) findviewbyid(r.id.send_dynamic); sendsystembtn = (button) findviewbyid(r.id.send_system); sendstaticbtn.setonclicklistener(new myonclicklistener()); senddynamicbtn.setonclicklistener(new myonclicklistener()); sendsystembtn.setonclicklistener(new myonclicklistener()); //申请读取短信的权限 permissionutil.requestpermission(mcontext, manifest.permission.read_sms, requestpermissiontype.request_code_ask_read_sms); permissionutil.requestpermission(mcontext, manifest.permission.receive_sms, requestpermissiontype.request_code_ask_receive_sms); } class myonclicklistener implements view.onclicklistener { @override public void onclick(view v) { // 发送自定义静态注册广播消息 if (v.getid() == r.id.send_static) { log.e("mainactivity", "发送自定义静态注册广播消息"); intent intent = new intent(); intent.setaction(staticaction); intent.putextra("msg", "接收静态注册广播成功!"); sendbroadcast(intent); } // 发送自定义动态注册广播消息 else if (v.getid() == r.id.send_dynamic) { log.e("mainactivity", "发送自定义动态注册广播消息"); intent intent = new intent(); intent.setaction(dynamicaction); intent.putextra("msg", "接收动态注册广播成功!"); sendbroadcast(intent); } // 发送系统动态注册广播消息。当手机连接充电设备时会由系统自己发送广播消息。 else if (v.getid() == r.id.send_system) { log.e("mainactivity", "发送系统动态注册广播消息"); intent intent = new intent(); intent.setaction(systemaction); intent.putextra("msg", "正在充电。。。。"); } } } @override protected void onstart() { super.onstart(); log.e("mainactivity", "注册广播事件"); // 注册自定义动态广播消息 intentfilter filter_dynamic = new intentfilter(); filter_dynamic.addaction(dynamicaction); registerreceiver(dynamicreceiver, filter_dynamic); // 注册系统动态广播消息 intentfilter filter_system = new intentfilter(); filter_system.addaction(systemaction); registerreceiver(systemreceiver, filter_system); } private broadcastreceiver dynamicreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { log.e("mainactivity", "接收自定义动态注册广播消息"); if (intent.getaction().equals(dynamicaction)) { string msg = intent.getstringextra("msg"); toast.maketext(context, msg, toast.length_short).show(); } } }; private broadcastreceiver systemreceiver = new broadcastreceiver() { @override public void onreceive(context context, intent intent) { log.e("mainactivity", "接收系统动态注册广播消息"); if (intent.getaction().equals(systemaction)) { string msg = intent.getstringextra("msg"); toast.maketext(context, msg, toast.length_short).show(); } } }; }
staticreceiver.java
package com.nii.receiver; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.os.handler; import android.widget.toast; /** * created by wzj on 2017/2/19. */ public class staticreceiver extends broadcastreceiver { /** * 接收广播 * @param context context * @param intent intent */ @override public void onreceive(context context, intent intent) { string msg = intent.getstringextra("msg"); toast.maketext(context, msg, toast.length_short).show(); } }
systemreceiver.java这里面处理一些系统的事件
package com.nii.receiver; import android.content.broadcastreceiver; import android.content.context; import android.content.intent; import android.os.bundle; import android.os.handler; import android.telephony.smsmessage; import android.text.format.dateformat; import android.util.log; import android.widget.toast; import com.nii.receiver.util.dialogutil; import java.util.date; /** * created by wzj on 2017/2/19. */ public class systemreceiver extends broadcastreceiver { /** * 接收系统静态广播 * * @param context context * @param intent intent */ @override public void onreceive(context context, intent intent) { if (intent.getaction().equals(intent.action_battery_low)) { log.e("systemreceiver", "电量低提示"); toast.maketext(context, "您的手机电量偏低,请及时充电", toast.length_short).show(); } else if (intent.getaction().equals("android.provider.telephony.sms_received")) { if (intent.getaction().equals("android.provider.telephony.sms_received")) { bundle bundle = intent.getextras(); if (bundle != null) {//如果数据不为空 //获得收到的短信数据 object[] objarray = (object[]) bundle.get("pdus"); //根据objarray的大小创建一个smsmessage数组,用于封装短信内容 smsmessage[] smsmessage = new smsmessage[objarray.length]; stringbuffer sb = new stringbuffer(); sb.append("时间:" + new dateformat().format("yyyy - mm - dd hh.mm.ss", new date())); //遍历smsmessage数组取出所有短信 for (int i = 0; i < smsmessage.length; i++) { //将每条字节类型的短信数据转换成smsmessage对象 smsmessage[i] = smsmessage.createfrompdu((byte[]) objarray[i]); //获取短信发送地址 sb.append("发送者:" + smsmessage[i].getoriginatingaddress()); //获取短信内容 sb.append("短信内容:" + smsmessage[i].getdisplaymessagebody() + "\n"); } dialogutil.showprompt(context,sb.tostring()); toast.maketext(context, sb.tostring(), toast.length_long).show(); } } } else if(intent.getaction().equals("android.hardware.usb.action.usb_state")) { if (intent.getextras().getboolean("connected")) { toast.maketext(context, "usb插入", toast.length_long).show(); } else { toast.maketext(context, "usb拔出", toast.length_long).show(); } } } }
requestpermissiontype.java是权限请求的时候,qequest code(请求码)
package com.nii.receiver.type; /** * created by wzj on 2017/2/19. */ public interface requestpermissiontype { /** * 请求打电话的权限码 */ int request_code_ask_call_phone = 100; /** * 请求接收短信息 */ int request_code_ask_receive_sms = 101; /** * 请求读短信 */ int request_code_ask_read_sms = 102; }
dialogutil.java是界面弹窗工具类
package com.nii.receiver.util; import android.app.activity; import android.app.alertdialog; import android.content.context; import android.content.dialoginterface; import android.view.windowmanager; /** * 对话框工具箱 * * @author xiaopan */ public class dialogutil { /** * 显示一个对话框 * * @param context 上下文对象,最好给activity,否则需要android.permission.system_alert_window * @param title 标题 * @param message 消息 * @param confirmbutton 确认按钮 * @param confirmbuttonclicklistener 确认按钮点击监听器 * @param centerbutton 中间按钮 * @param centerbuttonclicklistener 中间按钮点击监听器 * @param cancelbutton 取消按钮 * @param cancelbuttonclicklistener 取消按钮点击监听器 * @param onshowlistener 显示监听器 * @param cancelable 是否允许通过点击返回按钮或者点击对话框之外的位置关闭对话框 * @param oncancellistener 取消监听器 * @param ondismisslistener 销毁监听器 * @return 对话框 */ public static alertdialog showalert(context context, string title, string message, string confirmbutton, dialoginterface.onclicklistener confirmbuttonclicklistener, string centerbutton, dialoginterface.onclicklistener centerbuttonclicklistener, string cancelbutton, dialoginterface.onclicklistener cancelbuttonclicklistener, dialoginterface.onshowlistener onshowlistener, boolean cancelable, dialoginterface.oncancellistener oncancellistener, dialoginterface.ondismisslistener ondismisslistener) { alertdialog.builder promptbuilder = new alertdialog.builder(context); if (title != null) { promptbuilder.settitle(title); } if (message != null) { promptbuilder.setmessage(message); } if (confirmbutton != null) { promptbuilder.setpositivebutton(confirmbutton, confirmbuttonclicklistener); } if (centerbutton != null) { promptbuilder.setneutralbutton(centerbutton, centerbuttonclicklistener); } if (cancelbutton != null) { promptbuilder.setnegativebutton(cancelbutton, cancelbuttonclicklistener); } promptbuilder.setcancelable(true); if (cancelable) { promptbuilder.setoncancellistener(oncancellistener); } alertdialog alertdialog = promptbuilder.create(); if (!(context instanceof activity)) { alertdialog.getwindow().settype(windowmanager.layoutparams.type_system_alert); } alertdialog.setondismisslistener(ondismisslistener); alertdialog.setonshowlistener(onshowlistener); alertdialog.show(); return alertdialog; } /** * 显示一个对话框 * * @param context 上下文对象,最好给activity,否则需要android.permission.system_alert_window * @param title 标题 * @param message 消息 * @param confirmbuttonclicklistener 确认按钮点击监听器 * @param cancelbuttonclicklistener 取消按钮点击监听器 * @return 对话框 */ public static alertdialog showconfirm(context context, string title, string message, dialoginterface.onclicklistener confirmbuttonclicklistener, dialoginterface.onclicklistener cancelbuttonclicklistener) { return showalert(context, title, message, "yes", confirmbuttonclicklistener, null, null, "no", cancelbuttonclicklistener, null, true, null, null); } /** * 显示一个提示框 * * @param context 上下文对象,最好给activity,否则需要android.permission.system_alert_window * @param message 提示的消息 * @param confirmbutton 确定按钮的名字 */ public static alertdialog showprompt(context context, string message, string confirmbutton) { return showalert(context, null, message, confirmbutton, null, null, null, null, null, null, true, null, null); } /** * 显示一个提示框 * * @param context 上下文对象,最好给activity,否则需要android.permission.system_alert_window * @param message 提示的消息 */ public static alertdialog showprompt(context context, string message) { return showalert(context, null, message, "ok", null, null, null, null, null, null, true, null, null); } }
permissionutil.java是权限申请工具类
package com.nii.receiver.util; import android.manifest; import android.app.activity; import android.content.context; import android.content.pm.packagemanager; import android.os.build; import android.support.v4.app.activitycompat; import android.support.v4.content.contextcompat; /** * created by wzj on 2017/2/19. */ public abstract class permissionutil { /** * 请求权限 * @param mcontext mcontext * @param permission permission * @param requestcode requestcode */ public static void requestpermission(context mcontext,string permission,int requestcode) { if (build.version.sdk_int < build.version_codes.m) { return; } int checkcallphonepermission = contextcompat.checkselfpermission(mcontext,permission); if (checkcallphonepermission != packagemanager.permission_granted) { activitycompat.requestpermissions((activity) mcontext, new string[]{permission},requestcode); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。