从零了解Firebase并进行实战

Firebase是个啥

服务端

  1. 添加依赖

    1
    2
    3
    4
    5
    <dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>9.2.0</version>
    </dependency>
  2. 在Firebase控制台,点击项目设置->服务账号->Firebase Admin SDK->选择java->生成新的私钥等待下载成功,复制下载成功的文件到项目里面

  3. 创建FireBaseConfig.java,添加初始化代码

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    import com.google.auth.oauth2.GoogleCredentials;
    import com.google.firebase.FirebaseApp;
    import com.google.firebase.FirebaseOptions;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    import java.io.FileInputStream;
    import java.io.IOException;

    @Component
    public class FireBaseConfig implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
    initFireBase();
    }

    private void initFireBase() throws IOException {
    //协议开放 克服握手错误
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
    System.out.println("协议开放成功: "+System.getProperty("https.protocols"));
    //firebase初始化
    FileInputStream refreshToken = new FileInputStream("path/to/serviceAccountKey.json"); //上一步下载的文件(私钥json)
    FirebaseOptions options = FirebaseOptions.builder()
    .setCredentials(GoogleCredentials.fromStream(refreshToken))
    .setDatabaseUrl("https://<DATABASE_NAME>.firebaseio.com/")
    .build();
    FirebaseApp.initializeApp(options);
    System.out.println("firebase初始化成功!!!");
    }
    }
  4. 创建工具类FireBaseUtils

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    import com.google.firebase.messaging.*;
    import java.util.Map;

    public class FireBaseUtils {
    public static String sendOne(String token, String title, String body, Map<String,String> data) throws FirebaseMessagingException {
    Message message = Message.builder()
    .setToken(token)
    // .setAndroidConfig(AndroidConfig.builder()
    // .setNotification(AndroidNotification.builder().setTitle(title).setBody(body).build()).build())
    .setNotification(Notification.builder().setTitle(title).setBody(body).build())
    .putAllData(data)
    // .setNotification(Notification.builder().build())
    .build();
    String result= FirebaseMessaging.getInstance().send(message);
    System.out.println("消息发送成功: "+result);
    return result;
    }
  5. 测试发送消息

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    @GetMapping("/send")
    public String send(){
    try {
    Map<String,String> data=new HashMap<>();
    data.put("allDataKey","allDataValue");
    //设备的token由客户端传过来
    return FireBaseUtils.sendOne("dtgeiUDK<设备的token>RVhF9:APAi1_xR4JQt5dELt",
    "我是标题","我是body",data);
    } catch (FirebaseMessagingException e) {
    throw new RuntimeException(e);
    }
    }

Firebase如何进行消息推送

  1. firebase控制台创建项目

  2. 产品类别->吸引->Messaging界面,点击添加应用

  3. 项目设置->常规->您的应用查看应用接入配置

    • web版本(未成功,应该是没有token的原因)

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      18
      19
      20
      21
      22
      import { initializeApp } from "firebase/app";
      import { getAnalytics } from "firebase/analytics";
      import { getMessaging, onMessage } from "firebase/messaging"; // 接入messaging模块

      const firebaseConfig = {
      apiKey: "AIxxx9HY",
      authDomain: "fir-502c5.firebaseapp.com",
      projectId: "fir-502c5",
      storageBucket: "fir-502c5.appspot.com",
      messagingSenderId: "47xxxx14",
      appId: "1:471967859514:web:b1d4axx6cac0d748603",
      measurementId: "G-FxxK"
      };

      // Initialize Firebase
      const app = initializeApp(firebaseConfig);
      const analytics = getAnalytics(app);

      const messaging=getMessaging(app); // 接入messaging模块
      onMessage(messaging, (payload) => {
      console.log('Message received. ', payload);
      });
    • Android

      可以使用 android studio再带的firebase进行集成,点击tools->firebase后续跟着提示操作即可。

      下面介绍手动版本:

      1. 引入依赖

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        //在项目(project)build.gradle添加com.google.gms.google-services依赖
        plugins {
        id 'com.android.application' version '8.2.0' apply false
        //添加依赖
        id 'com.google.gms.google-services' version '4.3.15' apply false
        }

        //在模块(module)build.gradle添加com.google.gms.google-services依赖
        plugins {
        id 'com.android.application'
        id 'com.google.gms.google-services'
        }
        ....
        dependencies {
        ....
        implementation(platform("com.google.firebase:firebase-bom:32.3.1"))
        implementation("com.google.firebase:firebase-analytics")
        implementation("com.google.firebase:firebase-inappmessaging")
        implementation("com.google.firebase:firebase-inappmessaging-display")
        }
      2. 添加获取token的方法,服务端发送消息的时候需要该token,一般在设备登录的时候把token发给服务端

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        FirebaseMessaging.getInstance().getToken()
        .addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
        if (!task.isSuccessful()) {
        Log.w(TAG, "Fetching FCM registration token failed", task.getException());
        return;
        }
        // Get new FCM registration token
        String token = task.getResult();
        // Log and toast
        String msg = "toke is: "+token;
        Log.i(TAG, msg);
        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        }
        });
      3. 添加接受消息的代码

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        21
        22
        23
        import android.util.Log;
        import androidx.annotation.NonNull;
        import com.google.firebase.messaging.FirebaseMessagingService;
        import com.google.firebase.messaging.RemoteMessage;

        public class MyFirebaseMessagingService extends FirebaseMessagingService {
        private static final String TAG="MyFirebaseMessagingService";
        @Override
        public void onNewToken(@NonNull String token) {
        Log.i(TAG,"Refreshed token: " + token);
        }
        @Override
        public void onMessageReceived(@NonNull RemoteMessage message) {
        Log.d(TAG, "From: " + message.getFrom());
        //From: 471967859514
        Log.d(TAG, "AllData: "+message.getData());
        //AllData: {allDataKey=allDataValue}
        Log.d(TAG, "Notification title: "+message.getNotification().getTitle());
        //Notification title: 我是标题
        Log.d(TAG, "Notification body: "+message.getNotification().getBody());
        //Notification body: 我是body
        }
        }
  4. 制作首个宣传活动(或者新建宣传活动)