Android 建立一個Notification

2018-08-02 18:09 更新

編寫:fastcome1985 - 原文:http://developer.android.com/training/notify-user/build-notification.html

創(chuàng)建Notification Buider

例如:


NotificationCompat.Builder mBuilder =
    new NotificationCompat.Builder(this)
    .setSmallIcon(R.drawable.notification_icon)
    .setContentTitle("My notification")
    .setContentText("Hello World!");

定義Notification的Action(行為)

  • 盡管在Notification中Actions是可選的,但是你應該至少添加一種Action。一種Action可以讓用戶從Notification直接進入你應用內的Activity,在這個activity中他們可以查看引起Notification的事件或者做下一步的處理。在Notification中,action本身是由PendingIntent定義的,PendingIntent包含了一個啟動你應用內ActivityIntent。

  • 如何構建一個PendingIntent取決于你要啟動的activity的類型。當從Notification中啟動一個activity時,你必須保存用戶的導航體驗。在下面的代碼片段中,點擊Notification啟動一個新的activity,這個activity有效地擴展了Notification的行為。在這種情形下,就沒必要人為地去創(chuàng)建一個返回棧(更多關于這方面的信息,請查看 Preserving Navigation when Starting an Activity


Intent resultIntent = new Intent(this, ResultActivity.class);
...
// Because clicking the notification opens a new ("special") activity, there's
// no need to create an artificial back stack.
PendingIntent resultPendingIntent =
    PendingIntent.getActivity(
    this,
    0,
    resultIntent,
    PendingIntent.FLAG_UPDATE_CURRENT
);

設置Notification的點擊行為

可以通過調用NotificationCompat.Builder中合適的方法,將上一步創(chuàng)建的PendingIntent與一個手勢產(chǎn)生關聯(lián)。比方說,當點擊Notification抽屜里的Notification文本時,啟動一個activity,可以通過調用setContentIntent())方法把PendingIntent添加進去。

例如:


PendingIntent resultPendingIntent;
...
mBuilder.setContentIntent(resultPendingIntent);

發(fā)布Notification

為了發(fā)布notification:

* 獲取一個[NotificationManager](http://www.baidu.com/baidu?wd=NotificationManager.&tn=monline_4_dg)實例
* 使用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法發(fā)布Notification。當你調用[notify()](developer.android.com/reference/java/lang/Object.html#notify())方法時,指定一個notification ID。你可以在以后使用這個ID來更新你的notification。這在[Managing Notifications](developer.android.com/intl/zh-cn/training/notify-user/managing.html)中有更詳細的描述。
* 調用[build()](developer.android.com/reference/android/support/v4/app/NotificationCompat.Builder.html#build())方法,會返回一個包含你的特征的[Notification](developer.android.com/reference/android/app/Notification.html)對象。

舉個例子:


NotificationCompat.Builder mBuilder;
...
// Sets an ID for the notification
int mNotificationId = 001;
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號