Push Notification với Firebase

Firebase là dịch vụ cơ sở dữ liệu hoạt động trên nền tảng đám mây. Kèm theo đó là hệ thống máy chủ cực kỳ mạnh mẽ của Google.

Tạo một project Firebase

Truy cập Firebase Console để tạo một project Firebase.

Thêm Android App vào project

Bước 1. Trong Firebase Project chọn thêm một ứng dụng Android và làm theo trình tự. Sau đó tải file google-services.json đặt tại thư mục android/app

Bước 2. Thêm classpath trong file <app-name>/android/build.gradle

dependencies {
  // Example existing classpath
  classpath 'com.android.tools.build:gradle:3.5.3'
  // Add the google services classpath
  classpath 'com.google.gms:google-services:4.3.2'
}

Bước 3. Thêm vào bên trong thẻ Activity trong file AndroidManifest.xml

<intent-filter>
      <action android:name="FLUTTER_NOTIFICATION_CLICK" />
      <category android:name="android.intent.category.DEFAULT" />
</intent-filter>

Bước 4. Thêm dependency trong file<app-name>/android/app/build.gradle

dependencies {
  // ...
  implementation 'com.google.firebase:firebase-messaging:17.3.3'
}

Bước 5. Thêm dòng apply plugin vào file <app-name>/android/app/build.gradle

// ADD THIS AT THE BOTTOM
apply plugin: 'com.google.gms.google-services'

Chỉnh sửa Icon thông báo trên thanh status:

Thêm một thẻ meta-data trong file AndroidManifest.xml

<meta-data android:name="com.google.firebase.messaging.default_notification_icon"
    android:resource="@drawable/ic_app_icon" />

Thêm file có tên ic_app_icon.png trong android/app/src/main/res/drawable

Thêm IOS App vào project

Bước 1: Trong Firebase Project chọn thêm một ứng dụng IOS và làm theo trình tự. Sau đó tải file google-services.json về máy. Chuột phải vào thư mục ios -> Flutter -> Open iOS module in XCode.

Open iOS module in Xcode

Chọn Add Files to "Runner" để thêm file google-services.json vào Project.

Add Files to "Runner"

Bước 2: Thêm trong file Info.plist

<key>FirebaseAppDelegateProxyEnabled</key>
<false/>

Bước 3: Kích hoạt Push Notifcations và Background Modes: Remote notifications trong Runner/Signing & Capabilities/ + Capability

Bước 4: Tạo một APNs Key cho ứng dụng tại đây.

Tạo APNs Key

Bước 5: Cấu hình APNs Key cho roject Firebase trong Setting/Cloud Messaging.

Upload APNs Key

Tích hợp vào Flutter

Tích hợp thông báo vào firebase bằng đoạn code bên dưới. Khuyến khích đặt trong màn hình chính sau khi đã đăng nhập.

 final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
 
  @override
  void initState() {
    super.initState();
    _fireBaseConfig();
  }

void _fireBaseConfig() {

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
      },
    );
    _firebaseMessaging.subscribeToTopic('all');

    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print('Token FCM : $token');
    });
  }

Trong đó:

  • onMessage: Được gọi khi nhận được thông báo trong quá trình chạy ứng dụng.

  • onLaunch: Được gọi khi người dùng nhấn vào thông báo trên điện thoại và chạy tới ứng dụng.

  • onResume: Được gọi khi ứng dụng được mở lên lại khi đang chạy ngầm.

  • subscribeToTopic: Hàm để đăng ký một kênh nghe thông báo. (Vd: all, vip, ...).

  • requestNotificationPermissionsonIosSettingsRegistered: Dùng để xin quyền nhận thông báo cho Ios.

  • getToken: Lấy ra token máy, dùng để xác định người nhận thông báo.

Last updated

Was this helpful?