PendingIntent 速記

什麼是PendingIntent,字面上來看就是 即將發生的intent。

我們知道如果要開始一個Intent,可以如下

Intent x1 = new Intent( this, xxx.class);
startActivity(x1);

通常我們是要開啟一個新的activity會用到Intent。我們更應該把 Intent理解為Activity間的一個訊息的傳遞。也就是由Intent這個信使,帶著訊息,告知Activity要啟動了。這樣理解,我們可以推論,Intent可以帶著訊息通知其它class,讓他們啟動。

如 Service
Intent x1 = new Intent(this, xxxService.class);
startService(x1);


但有時候,我們有一個Intent,我們不想用 startActivity, 或是 startService去啟動,而是希望它等待至某種要求出現才啟動。這就需要用到 PendingIntent。

所以簡單的說,PendingIntent就是把一個已知的 Intent 包起來。然後pending(即將發生)。
我們看一下PendingIntent有幾個靜態方法

包了一個Activity的Intent
public static PendingIntent getActivity(Context context, int requestCode, Intent intent, int flags)
包了一個Broadcast的Intent
public static PendingIntent getBroadcast(Context context, int requestCode, Intent intent, int flags)
包了一個Service的Intent
public static PendingIntent getService(Context context, int requestCode, Intent intent, int flags)
包了多個Activity的Intent
public static PendingIntent getActivities(Context context, int requestCode, Intent[] intents, int flags)
包了多個Activity的Intent 加上 Bundle。
public static PendingIntent getActivities(Context context, int requestCode, Intent[] intents, int flags, Bundle options)


這樣我們就能理解,為什麼Notification會需要用到PendingIntent。因為這個Pending(即將發生),是由Notification來觸發。以下我們看一個Notification的範例。


if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { CharSequence name = "自己設一個名字"; String description ="自己描述一下是什麼Notification"; int importance = NotificationManager.IMPORTANCE_DEFAULT; NotificationChannel channel = new NotificationChannel("這是CHANNEL ID,自己設", name, importance); channel.setDescription(description); // Register the channel with the system; you can't change the importance // or other notification behaviors after this mNManager = getSystemService(NotificationManager.class); mNManager.createNotificationChannel(channel); }else { mNManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); } Intent x1 = new Intent (context, xxxActivity.class); x1.putExtra("str", "自帶文字"); PendingIntent pX1 = PendingIntent.getActivity(context, 0, x1, PendingIntent.FLAG_CANCEL_CURRENT); Notification.Builder mBuilder = new Notification.Builder(context); mBuilder.setContentTitle(getResources().getString(R.string.XXXXX)) //標題 .setContentText(自己設的文字") //內容 .setSubText("自己設的文字") //内容下面一小段註明 .setTicker("自己設的文字") //狀態欄顯示的文字 .setWhen(System.currentTimeMillis()) //時間 .setSmallIcon( R.drawable.XXXX) //狀態欄之小圖 //.setLargeIcon( R.drawable.xxxx) //大圖 .setDefaults(Notification.DEFAULT_LIGHTS ) //設置提醒通知 .setAutoCancel(true) //點擊後是否消失 .setContentIntent(pX1); //點擊後啟動 PendingIntent notify1 = mBuilder.build(); mNManager.notify(1, notify1);

留言

這個網誌中的熱門文章

python 找圖自動點擊

Python pyserial 抓取系統內的 COM PORT

VBA EXCEL 工作表變化 馬上執行 的作法 Worksheet_Change