[Android] Android 學習筆記:顯示 notification 提示訊息

[Android] Android 學習筆記:顯示 notification 提示訊息

Android 上一個很常見的應用是秀 notification 提示訊息,

這個提示訊息會在手機最上面捲動顯示一次,然後也會留在 notification 列表裡~

什麼時候會使用到 notification 呢?這就依各種 app 的情況而定了~

有的 app 會在有更新的時候自動送個 notification,

而比較常見的是 app 在背景中執行,但有某件事情需要通知使用者的時候,也可以用notification~

 

要使用 notification,主要是要建立出一個 Notification 物件,

指定要顯示的訊息,同時也指定說如果使用者點下了這個訊息,要如何反應~

常見的作法可能是跳出原本 app 的畫面~或者是點下就代表確認要做某件事之類的…

真正要做的事情要用一個 Intent 包起來(像這是回到 Home 主畫面的 intent 範例),

但因為這件事情要等到使用者按下訊息才會做,

因此還要先用 PendingIntent 包起來,才能指定給 notification~

 

下面的範例程式,在呼叫 showNotification() 時,會顯示出以 sMsg 為內容的訊息,

因為我們給了一個空的 intent,因此使用者點下訊息後,

什麼事也不會做,只會把那個訊息清掉而已~~

package com.my;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;

import com.my.R;

public class MyActivity extends Activity {
   
    // Private variables
    private static int      s_nNotificationId   = 0;
       
    public void showNotification(String sMsg)
    {
        // Create an intent that does nothing
        Intent intentNotify = new Intent();

        // Prepare the pending-intent for the notification,
        //  and let it trigger intentNotify, which does nothing
        PendingIntent intentContent = PendingIntent.getActivity(MyActivity.this, 0, intentNotify, 0);
       
        // Create notification.
        //  The string will be shown on top bar of device.
        Notification notification = new Notification(R.drawable.ic_launcher, getString(R.string.app_name) + “: “ + sMsg, System.currentTimeMillis());
       
        // The notification will disappear automatically when user clicks it
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
       
        // Here sets the title and message of the notification,
        //  which will be shown in the dropdown notification list.
        notification.setLatestEventInfo(MyActivity.this, getString(R.string.app_name), sMsg, intentContent);

        // Send out notify
        NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        notificationManager.notify(s_nNotificationId++, notification);
    }    
}
 

 

 

(本頁面已被瀏覽過 530 次)

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料