Friday, September 11, 2015

Android Notification (căn bản về thông báo trong Android)

Notification là dạng thông báo xuất hiện ở phần trên cùng của màn hình, dạng thông báo này hiện giời được hỗ trợ trên cả 3 nền tảng phổ biến hiện này: Android, iOS và WindowPhone.



Android cung cấp thư viện NotificationCompat.Builder, Notification để tạo các thông báo này.

  1. NotificationCompat.Builder.build(): để tạo một thông báo

  2. Phương thức notify() của Notification: để cập nhật thông báo

  3. setSmalIcon: chỉ định icon của thông báo

  4. setContentTitle: Tiêu đề thông báo

  5. setContentText: Nội dung thông báo



Ví dụ tạo một thông báo:
[sourcecode language="java"]
Notification.Builder mBuilder = new Notification.Builder(this);
mBuilder.setContentTitle("Tin nhắn mới");
mBuilder.setContentText("Có điểm thực hành môn Android.");
mBuilder.setTicker("Thông báo!"); mBuilder.setSmallIcon(R.drawable.ic_launcher);
[/sourcecode]

Cập nhật thông báo
[sourcecode language="java"]
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
/* cập nhật thông báo */
mNotificationManager.notify(notificationID, mBuilder.build());
[/sourcecode]

Thông thường các ứng dụng cấu hình khi người dùng chạm lên thông báo thì hệ thống sẽ mở lại ứng dụng đã phát sinh thông báo. Để Android có thể mở lại một ứng dụng đã thông báo (có thể là bất kỳ ứng dụng nào) hợp lệ thì chúng ta cần phải thông qua đối tượng hỗ trợ là PendingIntent

Ví dụ sau đây thực hiện theo mô tả bên trên.

[sourcecode language="java"]
/* Tạo đối tượng chỉ đến activity sẽ mở khi chọn thông báo */
Intent resultIntent = new Intent(this, NotificationView.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationView.class);
// kèm dữ liệu theo activity để xử lý
resultIntent.putExtra("events",new String[] { "Có điểm thực hành môn Android" });
resultIntent.putExtra("id",notificationID);
/* Đăng ký activity được gọi khi chọn thông báo */
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
[/sourcecode]

Sau khi mở ứng dụng (NotificationView) đã phát sinh thông báo qua hỗ trợ của PendingIntent chúng ta có thể xóa thông báo báo với phương thức cancel từ NotificartioManager

Ví dụ như sau:
[sourcecode language="java"]
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.cancel(i.getIntExtra("id", 0));
[/sourcecode]

Notification có 2 dạng cơ bản là dạng đơn và dạng danh sách.
Ví dụ:
Snap 2015-09-10 at 16.57.29
Mã nguồn ở
đây

No comments:

Post a Comment

Translate