1、PendingIntent作用
根據(jù)字面意思就知道是延遲的intent,主要用來在某個(gè)事件完成后執(zhí)行特定的Action。PendingIntent包含了Intent及Context,所以就算Intent所屬程序結(jié)束,PendingIntent依然有效,可以在其他程序中使用。
常用在通知欄及短信發(fā)送系統(tǒng)中。
PendingIntent一般作為參數(shù)傳給某個(gè)實(shí)例,在該實(shí)例完成某個(gè)操作后自動(dòng)執(zhí)行PendingIntent上的Action,也可以通過PendingIntent的send函數(shù)手動(dòng)執(zhí)行,并可以在send函數(shù)中設(shè)置OnFinished表示send成功后執(zhí)行的動(dòng)作。
2.舉例(通知欄應(yīng)用)
界面A 定義一個(gè)notification
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification;
long when = System.currentTimeMillis()+2000;
Notification n = new Notification(icon,"標(biāo)題",when);
n.defaults = Notification.DEFAULT_SOUND;
n.flags |= Notification.FLAG_AUTO_CANCEL;
Intent intent = new Intent(this,B.class);
PendingIntent pi = new PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
n.setLatesEventInfo(this,"通知欄demo提醒title","通知欄demo提醒text",pi);
nm.notify(0,n);
B.界面Intent intent = getIntent();
String title = intent.getStringExtra("title");
效果,當(dāng)A界面顯示,生成一個(gè)按鈕,點(diǎn)擊該按鈕生成如上所示的通知欄,點(diǎn)擊通知欄,則顯示B界面,參數(shù)title為所顯示的值。
3、Intent和PendingIntent的區(qū)別
a. Intent是立即使用的,而PendingIntent可以等到事件發(fā)生后觸發(fā),PendingIntent可以cancel
b. Intent在程序結(jié)束后即終止,而PendingIntent在程序結(jié)束后依然有效
c. PendingIntent自帶Context,而Intent需要在某個(gè)Context內(nèi)運(yùn)行
d. Intent在原task中運(yùn)行,PendingIntent在新的task中運(yùn)行