android点滴之PendingIntent的使用

时间:2023-03-08 21:54:31

一概念

PendingIntent就是一个能够在满足一定条件下运行的Intent,它相比于Intent的优势在于自己携带有Context对象。这样他就不必依赖于某个activity才干够存在。
它和Intent的主要差别在于Intent的运行立马的,而pendingIntent的运行不是立马的。pendingIntent运行的操作实质上是參数传进来的Intent的操作。可是使用pendingIntent的目的在于它所包括的Intent的操作的运行是须要满足某些条件的。

二实质

PendingIntent能够看作是对Intent的包装。PendingIntent主要持有的信息是它所包装的Intent和当前Application的Context。

正因为PendingIntent中保存有当前Application的Context,使它赋予带他程序一种运行的Intent的能力,就算在运行时当前Application已经不存在了,也能通过存在PendingIntent里的Context照样运行Intent。

三常见使用场景及代码

1.定时闹钟
PendingIntent pi1 = PendingIntent.getBroadcast(context,AutoTimeringBroadcast1.class,1);//创建意图
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,time,1000*60*60*24, pi);//time为目标时间毫秒值。反复运行就可以

2.通知点击打开界面

NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)
int icon = android.R.drawable.stat_notify_chat;
long when = System.currentTimeMillis();//通知发生的时间为系统当前时间
//新建一个通知,指定其图标和标题
Notification notification = new Notification(icon, null, when);//第一个參数为图标,第二个參数为短暂提示标题,第三个为通知时间
notification.defaults = Notification.DEFAULT_SOUND;//发出默认声音
notification.flags |= Notification.FLAG_AUTO_CANCEL;//点击通知后自己主动清除通知
Intent openintent = new Intent(this, OtherActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, openintent, 0);//当点击消息时就会向系统发送openintent意图
notification.setLatestEventInfo(this, “标题”, “我是内容", contentIntent);//点击后做的事情就是contentIntent的任务 mNotificationManager.notify(0, notification);//第一个參数为自己定义的通知唯一标识,发出这个通知!

3.发送短信后获取回执

SmsManager的用于发送短信的方法:

sendTextMessage(destinationAddress, scAddress, text, sentIntent, deliveryIntent);

第一个參数:destinationAddress 对方手机号码

第二个參数:scAddress 短信中心号码 一般设置为空

第三个參数:text 短信内容

第四个參数:sentIntent推断短信是否发送成功,假设你没有SIM卡,或者网络中断。则能够通过这个itent来推断。注意强调的是“发送”的动作是否成功。

那么至于对于对方是否收到,另当别论

第五个參数:deliveryIntent当短信发送到收件人时。会收到这个deliveryIntent。即强调了“发送”后的结果

就是说是在"短信发送成功"和"对方收到此短信"才会激活 sentIntent和deliveryIntent这两个Intent。

这也相当于是延迟运行了Intent