標籤:pendingintent android 簡訊 鬧鐘
一概念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