博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android中pendingIntent的深入理解
阅读量:4708 次
发布时间:2019-06-10

本文共 7735 字,大约阅读时间需要 25 分钟。

pendingIntent字面意义:等待的。未决定的Intent。

要得到一个pendingIntent对象,用法类的静态方法 ,,

參数有4个,比較重要的事第三个和第一个,其次是第四个和第二个。能够看到。要得到这个对象,必须传入一个Intent作为參数。必须有context作为參数。
pendingIntent是一种特殊的Intent。基本的差别在于Intent的运行立马的,而pendingIntent的运行不是立马的。pendingIntent运行的操作实质上是參数传进来的Intent的操作,可是使用pendingIntent的目的在于它所包括的Intent的操作的运行是须要满足某些条件的。
基本的使用的地方和样例:通知Notificatio的发送,短消息SmsManager
的发送和警报器AlarmManager的运行等等。

Android的状态栏通知(Notification)

假设须要查看消息。能够拖动状态栏到屏幕下方就可以查看消息。

步骤:

1获取通知管理器NotificationManager,它也是一个系统服务

2建立通知Notification notification = new Notification(icon, null, when);

3为新通知设置參数(比方声音。震动,灯光闪烁)

4把新通知加入到通知管理器

发送消息的代码例如以下:

//获取通知管理器

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);

mNotificationManager.notify(0, notification);//第一个參数为自己定义的通知唯一标识

 

重点是setLatestEventInfo( )方法的最后一个參数!!!!它是一个PendingIntent!!!!!!!!!

这里使用到了PendingIntent(pend本意是待定。不确定的意思)

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

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

 

PendingIntent的一个非常好的样例:

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

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

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

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

第三个參数:text短信内容

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

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

就是说是在"短信发送成功""对方收到此短信"才会激活 sentIntentdeliveryIntent这两个Intent。这也相当于是延迟运行了Intent

上面两个样例能够理解。PendingIntent就是一个能够在满足一定条件下运行的Intent,它相比于Intent的优势在于自己携带有Context对象,这样他就不必依赖于某个activity才干够存在。

//

本文主要介绍PendingIntent的作用举例以及和Intent的差别,本文中代码见。

1、PendingIntent作用

依据字面意思就知道是延迟的intent,主要用来在某个事件完毕后运行特定的Action。PendingIntent包括了Intent及Context,所以就算Intent所属程序结束,PendingIntent依旧有效。能够在其它程序中使用。

经常使用在通知栏及短信发送系统中。

PendingIntent一般作为參数传给某个实例,在该实例完毕某个操作后自己主动运行PendingIntent上的Action,也能够通过PendingIntent的send函数手动运行,并能够在send函数中设置OnFinished表示send成功后运行的动作。

2、PendingIntent举例

a. 系统通知栏

NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);int icon = android.R.drawable.stat_notify_chat;long when = System.currentTimeMillis() + 2000;Notification n = new Notification(icon, "通知栏demo提醒", when);n.defaults = Notification.DEFAULT_SOUND;n.flags |= Notification.FLAG_AUTO_CANCEL;Intent openintent = new Intent(this, DemoList.class);PendingIntent pi = PendingIntent.getActivity(this, 0, openintent, PendingIntent.FLAG_CANCEL_CURRENT);n.setLatestEventInfo(this, "通知栏demo提醒title", "通知栏demo提醒text", pi);nm.notify(0, n);

setLatestEventInfo表示设置点击该通知的事件

b. 短信系统举例

短信系统举例代码
private final static String SEND_ACTION      = "send";private final static String DELIVERED_ACTION = "delivered";private void sendSms(String receiver, String text) {    SmsManager s = SmsManager.getDefault();    PendingIntent sentPI = PendingIntent.getBroadcast(this, 0, new Intent(SEND_ACTION),                                                      PendingIntent.FLAG_CANCEL_CURRENT);    PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0, new Intent(DELIVERED_ACTION),                                                           PendingIntent.FLAG_CANCEL_CURRENT);    // 发送完毕    registerReceiver(new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            switch (getResultCode()) {                case Activity.RESULT_OK:                    Toast.makeText(getBaseContext(), "Send Success!", Toast.LENGTH_SHORT).show();                    break;                case SmsManager.RESULT_ERROR_GENERIC_FAILURE:                    Toast.makeText(getBaseContext(), "Send Failed because generic failure cause.",                                   Toast.LENGTH_SHORT).show();                    break;                case SmsManager.RESULT_ERROR_NO_SERVICE:                    Toast.makeText(getBaseContext(), "Send Failed because service is currently unavailable.",                                   Toast.LENGTH_SHORT).show();                    break;                case SmsManager.RESULT_ERROR_NULL_PDU:                    Toast.makeText(getBaseContext(), "Send Failed because no pdu provided.", Toast.LENGTH_SHORT).show();                    break;                case SmsManager.RESULT_ERROR_RADIO_OFF:                    Toast.makeText(getBaseContext(), "Send Failed because radio was explicitly turned off.",                                   Toast.LENGTH_SHORT).show();                    break;                default:                    Toast.makeText(getBaseContext(), "Send Failed.", Toast.LENGTH_SHORT).show();                    break;            }        }    }, new IntentFilter(SEND_ACTION));    // 对方接受完毕    registerReceiver(new BroadcastReceiver() {        @Override        public void onReceive(Context context, Intent intent) {            switch (getResultCode()) {                case Activity.RESULT_OK:                    Toast.makeText(getBaseContext(), "Delivered Success!", Toast.LENGTH_SHORT).show();                    break;                default:                    Toast.makeText(getBaseContext(), "Delivered Failed!", Toast.LENGTH_SHORT).show();                    break;            }        }    }, new IntentFilter(DELIVERED_ACTION));    // 发送短信。sentPI和deliveredPI将分别在短信发送成功和对方接受成功时被广播    s.sendTextMessage(receiver, null, text, sentPI, deliveredPI);}

以上的两个PendingIntent sentPI和deliveredPI将分别在短信发送成功和对方接受成功时被广播

3、Intent和PendingIntent的差别

a. Intent是马上使用的,而PendingIntent能够等到事件发生后触发,PendingIntent能够cancel

b. Intent在程序结束后即终止。而PendingIntent在程序结束后依旧有效
c. PendingIntent自带Context,而Intent须要在某个Context内执行
d. Intent在原task中执行。PendingIntent在新的task中执行

///

PendingIntent用于描写叙述Intent及其终于的行为. 
        你能够通过getActivity(Context context, int requestCode, Intent intent, int flags)系列方法从系统取得一个用于启动一个Activity的PendingIntent对象,

       能够通过getService(Context context, int requestCode, Intent intent, int flags)方法从系统取得一个用于启动一个Service的PendingIntent对象

        能够通过getBroadcast(Context context, int requestCode, Intent intent, int flags)方法从系统取得一个用于向BroadcastReceiver的Intent广播的PendingIntent对象

         返回的PendingIntent能够递交给别的应用程序,然后继续处理。这里的话你能够稍后才处理PendingIntent中描写叙述的Intent及其终于行为。

        当你把PendingIntent递交给别的程序进行处理时,PendingIntent仍然拥有PendingIntent原程序所拥有的权限(with the same permissions and identity).当你从系统取得一个PendingIntent时,一定要很小心才行。比方。通常。假设Intent目的地是你自己的component(Activity/Service/BroadcastReceiver)的话,你最好採用在Intent中显示指定目的component名字的方式,以确保Intent终于能发到目的,否则Intent最后可能不知道发到哪里了。

一个PendingIntent就是Android系统中的一个token(节点。这个应该是Linux或C\C++用语)的一个对象引用,它描写叙述了一些将用于retrieve的数据(这里,这些数据描写叙述了Intent及其终于的行为)。

        这就意味着即使PendingIntent原进程结束了的话, PendingIntent本身仍然还存在,可在其它进程(PendingIntent被递交到的其它程序)中继续使用.假设我在从系统中提取一个PendingIntent的,而系统中有一个和你描写叙述的PendingIntent对等的PendingInent, 那么系统会直接返回和该PendingIntent事实上是同一token的PendingIntent,而不是一个新的token和PendingIntent。然而你在从提取PendingIntent时。通过FLAG_CANCEL_CURRENT參数,让这个老PendingIntent的先cancel()掉,这样得到的pendingInten和其token的就是新的了。

       通过FLAG_UPDATE_CURRENT參数的话,能够让新的Intent会更新之前PendingIntent中的Intent对象数据,比如更新Intent中的Extras。另外,我们也能够在PendingIntent的原进程中调用PendingIntent的cancel ()把其从系统中移除掉。

相关文章:

  绝对干货

我也碰到同样问题,详见备注

posted on
2017-07-09 16:06 阅读(
...) 评论(
...)

转载于:https://www.cnblogs.com/mthoutai/p/7141810.html

你可能感兴趣的文章
关于MySQL的行转列的简单应用
查看>>
Queue 队列的用法
查看>>
CDM常用命令
查看>>
游戏开发中常用的设计模式
查看>>
Linux 中/etc/profile、~/.bash_profile 环境变量配置及执行过程
查看>>
JAVA:图形之利用FontMetrics类居中
查看>>
使用rsync同步目录
查看>>
[读码时间] for循环遍历设置所有DIV块元素背景色为红色
查看>>
网页调用迅雷下载文件
查看>>
Python 调用 Shell命令
查看>>
POJ 1159 Palindrome(最长公共子序列)
查看>>
责任链模式(chain of responsibility)
查看>>
[转载]java多线程学习-java.util.concurrent详解(一) Latch/Barrier
查看>>
ionic - 运行起来
查看>>
Shell 输入/输出重定向
查看>>
数据结构与算法分析(C++)读书笔记
查看>>
(转)nginx应用总结(1)--基础认识和应用参数优化配置
查看>>
(转)关于sql和MySQL的语句执行顺序(必看!!!)
查看>>
UVALive 3668 A Funny Stone Game(博弈)
查看>>
信息论随笔2: 交叉熵、相对熵
查看>>