Intent和PendingIntent的關系?
Intent和PendingIntent的關系越看越迷惑,花了一段時間分析Android的JavaDoc終于有點心得,在此與大家分享:?
Intent是一個意圖,一個描述了想要啟動一個Activity、Broadcast或是Service的意圖。它主要持有的信息是它想要啟動的組件(Activity、Broadcast或是Service)。?
PendingIntent可以看作是對Intent的包裝。供當前App之外的其他App調用。有點“被動”或是“Callback”的意思,但不是嚴格意義上的“被動”或是“Callback”。總之,當前App不能用它馬上啟動它所包裹的Intent。而是在外部App執行這個 PendingIntent時,間接地、實際地調用里面的Intent。PendingIntent主要持有的信息是它所包裝的Intent和當前App 的Context。正由于PendingIntent中保存有當前App的Context,使它賦予外部App一種能力,使得外部App可以如同當前 App一樣的執行PendingIntent里的Intent,就算在執行時當前App已經不存在了,也能通過存在PendingIntent里的 Context照樣執行Intent。?
比較難理解,希望大家多提意見!?
- Notification?n?=? new ?Notification(R.drawable.face_1,? "Service啟動" ,?System.currentTimeMillis());??
- PendingIntent?contentIntent?=?PendingIntent.getActivity( this ,? 0 ,? new ?Intent( this ,?TServiceHolder. class ),? 0 );??
- n.setLatestEventInfo( this ,? "任務標題" ,? "任務內容" ,?contentIntent);??
- nManager.notify(NOTIFICATION_ID,?n);? //?任務欄啟動 ??
PendingIntent和Intent的區別:An Intent is something that is used right now; a PendingIntent is something that may create an Intent in the future. You will use a PendingIntent with Notifications, AlarmManager, etc.?
1. GSM網絡中android發送短信示例?
(1)代碼節選?
- String?msg?= "你好,美女" ;??
- String?number?=? "135****6784" ;??
- SmsManager?sms?=?SmsManager.getDefault();??
- ??
- PendingIntent?pi?=?PendingIntent.getBroadcast(SmsActivity. this , 0 , new ?Intent(...), 0 );??
- sms.sendTextMessage(number,? null ,?msg,?pi,? null );??
- Toast.makeText(SmsActivity. this , "發送成功" ,Toast.LENGHT_LONG).show();??
(2)代碼解釋?
????? PendingIntent就是一個Intent的描述,我們可以把這個描述交給別的程序,別的程序根據這個描述在后面的別的時間做你安排做的事情 (By giving a PendingIntent to another application, you are granting it the right to perform the operation you have specified as if the other application was yourself,就相當于PendingIntent代表了Intent)。本例中別的程序就是發送短信的程序,短信發送成功后要把intent廣播出去 。?
????? 函數SmsManager.sendTextMessage(String destinationAddress, String scAddress, String text, PendingIntent sentIntent, PendingIntent deliveryIntent)中參數解釋:?
????? 1)PendingIntent sentIntent:當短信發出時,成功的話sendIntent會把其內部的描述的intent廣播出去,否則產生錯誤代碼并通過 android.app.PendingIntent.OnFinished進行回調,這個參數最好不為空,否則會存在資源浪費的潛在問題;?
????? 2)PendingIntent deliveryIntent:是當消息已經傳遞給收信人后所進行的PendingIntent廣播。?
????? 查看PendingIntent 類可以看到許多的Send函數,就是PendingIntent在進行被賦予的相關的操作。?
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
