Sunday, January 13, 2019

Xử lý sự kiện với notification

Trong bài trước ta đã biết cách mở ra class mới từ notification, nay ta sẽ tìm cách cập nhật service từ notification.
Cụ thể, khi người dùng chạm vào notification để xoá, ta sẽ thoát service.
Tạo một class tên là NotificationDeleteReceiver.
public class NotificationDeleteReceiver extends BroadcastReceiver {
    @Override
  public void onReceive(Context context,Intent intent) {
       
context.stopService(new Intent(context,service.class));
    }
}
Trong file manifest.xml, thêm đoạn sau vào trên dòng </application> cuối cùng.
<receiver android:name="NotificationDeleteReceiver" />
Sau đó trong class mà ta tạo notification, copy hàm sau vào.
public void noti(String title, String message) {
Intent intent = new Intent(this, NotificationDeleteReceiver.class);
intent.putExtra("com.example.vidu", 1);

PendingIntent resultPendingIntent =
                PendingIntent.getBroadcast(this.getApplicationContext(),
                                           1, intent, 0);
NotificationCompat.Builder b = new NotificationCompat.Builder(this);
         b.setAutoCancel(true)
                 .setDefaults(NotificationCompat.DEFAULT_ALL)
                 .setWhen(System.currentTimeMillis())
                 .setSmallIcon(R.drawable.ic_launcher)
                 .setTicker("Đã ghi chú")
                 .setContentTitle(title)
                 .setContentText(message)
                 .setOngoing(true).setContentIntent(resultPendingIntent).setAutoCancel(true);
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
         nm.notify(1338, b.build());
   }
Khi gọi hàm để tạo notification.
noti("Lưu ý","nội dung cần chú ý");

Bây giờ khi người dùng chạm để xoá notification, service đang chạy cũng sẽ dừng.

No comments:

Post a Comment