3-AII--BroadcastReceiver实现锁、开屏、短信监听
标签:
JavaScript
零、前言
1.按电源键,屏幕锁屏,再按电源键屏幕打开。在Activity开启时注册广播用来监听屏幕的关闭,Activity关闭时移除广播。
2.这里只能在该Activity中监听,退出后BroadcastReceiver被注销,后面将会结合Service增强应用范围
3.后面也会结合传感器进行摇晃开屏,暗环境锁屏功能
4.短信监听,可以当收到短信时处理,比如提醒、备份、上传网络、删除、自动回复等
BroadcastReceiver实现锁屏及开屏监听.gif
一、代码实现
1:InnerActivity.java
public class InnerActivity extends AppCompatActivity { private ScreenReceiver mScreenReceiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_gary); ButterKnife.bind(this); regist(); } /** * 动态的去注册屏幕解锁和锁屏的广播 */ private void regist() { // [1]动态的去注册屏幕解锁和锁屏的广播 mScreenReceiver = new ScreenReceiver(); // [2]创建intent-filter对象 IntentFilter filter = new IntentFilter(); // [3]添加要注册的action filter.addAction("android.intent.action.SCREEN_OFF"); filter.addAction("android.intent.action.SCREEN_ON"); // [4]注册广播接收者 registerReceiver(mScreenReceiver, filter); } @Override protected void onDestroy() { super.onDestroy(); //当activity销毁的时候 取消注册广播接收者 unregisterReceiver(mScreenReceiver); } }
2:广播接收者:ScreenReceiver.java
public class ScreenReceiver extends BroadcastReceiver { private static final String TAG = "ScreenReceiver"; @Override public void onReceive(Context context, Intent intent) { //[1]获取到当前广播的事件类型 String action = intent.getAction(); //[2]对当前广播事件类型做一个判断 if ("android.intent.action.SCREEN_OFF".equals(action)) { Log.i(TAG, "屏幕锁屏了"); } else if ("android.intent.action.SCREEN_ON".equals(action)) { Log.i(TAG, "屏幕解锁了"); } } }
二、短信监听
1、InnerActivity#regist
//注册短信广播接收者IntentFilter smsFilter = new IntentFilter(); smsFilter.addAction("android.provider.Telephony.SMS_RECEIVED"); mSmsReceiver = new SmsReceiver(); registerReceiver(mSmsReceiver, smsFilter);
2、InnerActivity#onDestroy
unregisterReceiver(mSmsReceiver);//注销短信广播接收者
3、短信广播接收者:SmsReceiver.java
public class SmsReceiver extends BroadcastReceiver { //当短信到来的时候 就会执行这个方法 @Override public void onReceive(Context context, Intent intent) { //[1]获取发短信送的号码 和内容 Object[] objects = (Object[]) intent.getExtras().get("pdus"); for (Object pdu : objects) { //[2]获取smsmessage实例 SmsMessage smsMessage = SmsMessage.createFromPdu((byte[]) pdu); //[3]获取发送短信的内容 String body = smsMessage.getMessageBody(); Date date = new Date(smsMessage.getTimestampMillis());//时间 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //[4]获取发送者 String address = smsMessage.getOriginatingAddress(); String receiveTime = format.format(date); Log.e("SmsReceiver", "body:" + body + "---" + address+"---"+receiveTime); } } }
4、添加权限
<!--添加权限--> <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission> <uses-permission android:name="android.permission.READ_SMS"></uses-permission>
5、安卓5.1,实验结果如下:(6.0以上注意动态权限)
E/SmsReceiver: body:hello---+8613167727310---2018-08-24 21:50:13
作者:张风捷特烈
链接:https://www.jianshu.com/p/7bba676c675f
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦