+3

Push Notification sử dụng Firebase Notification trong ứng dụng Android

GIỚI THIỆU

Firebase Notification là một dịch vụ miễn phí của Firebase mà bạn có thể dùng nó để Push Notifications đến các thiết bị di động của người dùng một cách nhanh chóng.

Firebase Notification được xây dựng trên Firebase Cloud Messaging và FCM SDK, cung cấp một lựa chọn cho các lập trình viên hay nhóm phát triển đang tìm kiếm một nền tảng gửi notification linh hoạt nhưng lại tối thiểu hóa công đoạn nghiên cứu và phát triển.

Nền tảng FCM còn cung cấp một giao diện điều khiển trực quan mạnh mẽ nơi mà bạn có thể cấu hình push notification mà không cần có một server nào khác.

Notifications tích hợp chặt chẽ với Firebase Analytics, cho phép bạn hướng notifications đến một bộ phận người dùng theo những tiêu chí nào đó. Hơn thế nữa bạn có thể hướng notifications đến một nhóm người dùng định trước theo ứng dụng, phiên bản hay ngôn ngữ mà họ sử dụng. Và cuối cùng bạn có thể hướng notification đến chính xác một người dùng nào đó mà bạn muốn.

Firebase Notifications hoạt động như thế nào?

notifications-overview.png

Bạn có thể sử dụng Notifications console GUI để soạn và gửi notification đến tất cả các người dùng mà bạn muốn một cách dễ dàng như bạn gửi tin nhắn SMS vậy. Bạn có thể nhìn thấy trên hình, có thể không xuất hiện một server nào của bạn giống như GCM.

Implement Path

  • Bước 1: Cài đặt FCM SDK thông qua dependency
  • Bước 2: Mở Notification Console soạn và gửi notification tới người dùng
  • Bước 3 (Optional) : Xử lý notification trên client-app

Cài đặt Notifications SDK trên Android

Trước hết bạn phải cài đặt Firebase SDK vào project. Thêm dependency classpath vào file build.gradle của project

 dependencies {
        classpath 'com.android.tools.build:gradle:2.1.0'
        classpath 'com.google.gms:google-services:3.0.0'
    }

Sau đó apply plugin google play service, thêm đoạn sau vào dòng cuối cùng file build.gradle của app, sau cả block dependencies.

apply plugin: 'com.google.gms.google-services'

Bước tiếp theo rất quan trọng đó là bạn phải vào Firebase Console và thêm một app mới sau đó tải file cấu hình tên là google-services.json và đặt vào trong thư mục app của project.

Để cài đặt Notification SDK vào ứng dụng bạn chỉ cần thêm dependency sau vào file build.gragle

dependencies {
   compile 'com.google.firebase:firebase-messaging:9.0.2'
}

Hoàn tất các bước trên bạn nhấn sync gradle là xong bạn có thể bắt đầu viết code handle việc nhận notifications.

Receive and Handle Notifications

Để có thể nhận được messages bạn chỉ cần implement một service extends từ FirebaseMessagingService và override lại method onMessageRecived.

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static final String TAG = "MyFirebaseMsgService";

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        Log.d(TAG, "From: " + remoteMessage.getFrom());
        Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
        sendNotification(remoteMessage.getNotification().getBody());
    }

    private void sendNotification(String messageBody) {
        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_stat_ic_notification)
                .setContentTitle("FCM Message")
                .setContentText(messageBody)
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);

        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
}

Trong manifest khai báo như sau:

 <service
     android:name=".MyFirebaseMessagingService">
         <intent-filter>
             <action android:name="com.google.firebase.MESSAGING_EVENT"/>
         </intent-filter>
 </service>

Push Notifications

Truy cập vào console sau đó vào app dashboard, bạn vào phần Notifications và soạn một notifications sau đó gửi đi. Công việc này mình nghĩ về cơ bản nó dễ ngang với bạn gửi một email trên Gmail. (hihi)

Screen Shot 2016-06-28 at 9.02.10 AM.png

Xin hết. Bạn có thể tìm hiểu thêm tại đây


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí