1、PendingIntent作用
根據字面意思就知道是延遲的intent,主要用來在某個事件完成后執行特定的Action。PendingIntent包含了Intent及Context,所以就算Intent所屬程序結束,PendingIntent依然有效,可以在其他程序中使用。
常用在通知欄及短信發送系統中。
PendingIntent一般作為參數傳給某個實例,在該實例完成某個操作后自動執行PendingIntent上的Action,也可以通過PendingIntent的send函數手動執行,并可以在send函數中設置OnFinished表示send成功后執行的動作。
2.舉例(通知欄應用)
界面A 定義一個notification
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.notification;
long when = System.currentTimeMillis()+2000;
Notification n = new Notification(icon,"標題",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");
效果,當A界面顯示,生成一個按鈕,點擊該按鈕生成如上所示的通知欄,點擊通知欄,則顯示B界面,參數title為所顯示的值。
3、Intent和PendingIntent的區別a. Intent是立即使用的,而PendingIntent可以等到事件發生后觸發,PendingIntent可以cancel
b. Intent在程序結束后即終止,而PendingIntent在程序結束后依然有效
c. PendingIntent自帶Context,而Intent需要在某個Context內運行
d. Intent在原task中運行,PendingIntent在新的task中運行
posted on 2013-05-22 15:34
Terry Zou 閱讀(245)
評論(0) 編輯 收藏 所屬分類:
Android