Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Intent 與 PendingIntent 到底差在哪?一次講清楚

編輯:關於 Android 程式設計

先從字面理解:Intent 的英文原意是「意圖」,而 Pending 表示「即將發生、尚未到來」的事情。顧名思義,PendingIntent 這個類別就是用来处理「即將執行的意圖」。

核心差異

最典型的例子是通知(Notification)中的頁面跳轉:使用者此刻不會立刻跳頁,而是等到未來某個時機點擊通知才觸發,這正是 PendingIntent 的用武之地。

Intent 是「即時啟動」的,它會隨所在的 Activity 一起消失;而 PendingIntent 則像是 Intent 的包裝,通常透過 getActivity、getBroadcast、getService 取得實例。當前的 Activity 並不會馬上啟動它內含的 Intent,而是等到外部執行這個 PendingIntent 時才呼叫其中的 Intent。

正因為 PendingIntent 保存了當前 App 的 Context,它賦予了外部 App 一種能力:讓外部 App 能如同本 App 一樣去執行 PendingIntent 裡的 Intent。即使執行時本 App 已經不存在,也能靠 PendingIntent 中的 Context 照樣執行,此外還能處理 Intent 執行後的後續動作。它常與 AlarmManager、NotificationManager 搭配使用。

簡單總結:Intent 一般用於 Activity、Service、BroadcastReceiver 之間傳遞資料;PendingIntent 則多用在 Notification 上,可理解為「延遲執行的 Intent」。

通知中的實際用法

private void showNotify(){ Notification notice=new Notification(); notice.icon=R.drawable.icon; notice.tickerText="您有一條新的信息"; notice.defaults=Notification.DEFAULT_SOUND; notice.when=10L; //notice.setLatestEventInfo(this, "通知", "開會啦", PendingIntent.getActivity(this, 0, null, 0)); notice.setLatestEventInfo(this, "通知", "開會啦", PendingIntent.getActivity(this, 0, new Intent(this,Activity2.class), 0));//即將跳轉頁面,還沒跳轉 NotificationManager manager=(NotificationManager)getSystemService(this.NOTIFICATION_SERVICE); manager.notify(0,notice); }

發送簡訊的應用

PendingIntent 就像是一份 Intent 的「描述書」,我們把這份描述交給別的程式,對方就能在未來的某個時間點,替我們執行這件被安排好的事情。以下以簡訊為例:

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.LENGTH_LONG).show();

sendTextMessage 方法的兩個 PendingIntent 參數分別是:

1)sentIntent:簡訊發出成功時,會把其內部描述的 Intent 廣播出去;失敗則產生錯誤碼並透過 PendingIntent.OnFinished 回呼。此參數最好不要為空,否則可能有資源浪費的隱憂。

2)deliveryIntent:當訊息成功傳遞給收信人之後所進行的 PendingIntent 廣播。

查閱 PendingIntent 類別可看到許多 send 方法,正是 PendingIntent 執行「被賦予的相關操作」的體現。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved