[Day28]初探Firebase Cloud Messaging for Flutter

大家好,今天要来尝试使用firebase_messaging,今天使用的是Android手机

首先到Firebase Console注册一个帐号,并建一个Project,注册你的应用程序,并下载google-services.json,放到android/app

接着在/android/build.gradle 加上classpath 'com.google.gms:google-services:4.3.2'

//省略部分程序
buildscript {
    ext.kotlin_version = '1.3.50'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:4.0.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.2'  //加的是这句
    }
}

在/android/app/build.gradle,中要加两行
dependencies中加上
implementation 'com.google.firebase:firebase-messaging:20.3.0'
最下方加上
apply plugin: 'com.google.gms.google-services'

//省略部分程序
dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'com.google.firebase:firebase-messaging:20.3.0'
}

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

新建一个Application.java

在app/src/main/kotlin/com/ignaciozhang/flutter_neflix_cover/Application.java
,内容如下

package com.ignaciozhang.flutter_neflix_cover; //这一行要改成自己的专案名称

import io.flutter.app.FlutterApplication;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService;
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin;

public class Application extends FlutterApplication implements PluginRegistrantCallback {
    @Override
    public void onCreate() {
        super.onCreate();
        FlutterFirebaseMessagingService.setPluginRegistrant(this);
    }

    @Override
    public void registerWith(PluginRegistry registry) {
        FirebaseMessagingPlugin.registerWith(registry.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
    }
}

AndroidManifest.xml

接着在AndroidManifest.xml中,application里面修改两处
第一个是要加入这一段

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

第二个是改名字

android:name=".Application"

改完的application应该会像这样

<application
        android:name=".Application"
        android:label="flutter_neflix_cover"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <!-- Displays an Android View that continues showing the launch screen
                 Drawable until Flutter paints its first frame, then this splash
                 screen fades out. A splash screen is useful to avoid any visual
                 gap between the end of Android's launch screen and the painting of
                 Flutter's first frame. -->
            <meta-data
              android:name="io.flutter.embedding.android.SplashScreenDrawable"
              android:resource="@drawable/launch_background"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="FLUTTER_NOTIFICATION_CLICK" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>

在main.dart中定义方法

这个是直接写在import的下方,

import 'package:firebase_messaging/firebase_messaging.dart';

Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) async {
  if (message.containsKey('data')) {
    // Handle data message
    final dynamic data = message['data'];
  }

  if (message.containsKey('notification')) {
    // Handle notification message
    final dynamic notification = message['notification'];
  }

  // Or do other work.
}

initState中调用_firebaseMessaging.configure

进入的第一个StatefulWidget的initState里面加上这段

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

    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        // _showItemDialog(message);
      },
      onBackgroundMessage: myBackgroundMessageHandler,
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        // _navigateToItemDetail(message);
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        // _navigateToItemDetail(message);
      },
    );
    
  }

测试

在firebase中进入cloud message,按照说明发送一个测试讯息
Day28
在Terminals中就看到,接到的讯息

I/flutter (28511): onMessage: {notification: {title: TEST, body: 测试通知文字}, data: {}}
I/flutter (28511): onMessage: {notification: {title: 测试2, body: 测试讯息2}, data: {}}

<<:  这些日子我学到的JavaScript:Day25- to-do list 练习

>>:  [Day 28]-【STM32系列】实作-伺服马达 SG- 90 PWM控制

CMoney工程师战斗营weekly1

上紧发条开始转动的一周 久违的早睡早起彷佛是回到学生时期的脚步,紧张的心情刺激肾上腺素分泌,就连作梦...

Day18 NiFi - 与 AWS Athena & AWS Redshift 对接设定

今天来介绍的是如何透过 NiFi 来与 Athena 和 Redshift 来取得或写入资料,其实两...

[DAY 18] 阿豪牛车庒冰糖猪脚

阿豪牛车庒冰糖猪脚 地点:台南市新营区公园路一段218号 时间:17:00~21:00 在南部有些店...

终章 - 资安碎碎念与心得

终章 - 资安碎碎念与心得 其实原本还有很多想打的鬼故事, 但碍於尺度与很难去识别化,最後还是觉得不...

vue-awesome-swiper swiper1跟2不能同步

各位前辈好 我使用vue-awesome-swiper 3.1.3 vue-cli3 最近想使用第一...