美文网首页
Android 接入 firebase 推送

Android 接入 firebase 推送

作者: Icy_Summer | 来源:发表于2021-11-18 17:52 被阅读0次
1. firebase后台配置注册应用。
2. 下载 Firebase Android 配置文件 google-services.json,将其添加到应用模块目录。
3. 配置 google-service 插件
  • project 级 builde.gradle 中添加:
buildscript {

  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }

  dependencies {
    // ...
    // Add the following line:
    classpath 'com.google.gms:google-services:4.3.10'  // Google Services plugin
  }
}

allprojects {
  // ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    // ...
  }
}
  • 应用模块儿级 build.gradle 添加:
apply plugin: 'com.android.application'

android {
  // ...
}
// Add the following line:
// on the last line
apply plugin: 'com.google.gms.google-services'  // Google Services plugin
4. 引入需要的 Firebase SDK
  • 应用模块级 build.gradle 中添加:
dependencies {
  // ...

  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:28.4.2')
// When using the BoM, you don't specify versions in Firebase library dependencies

  // Declare the dependency for the Firebase SDK for Google Analytics
  implementation 'com.google.firebase:firebase-analytics'

  // Declare the dependencies for any other desired Firebase Products
  // 推送
  implementation 'com.google.firebase:firebase-messaging'

5. 配置 AndroidMainfest.xml
  • 注册一个继承 FirebaseMessagingService 的 service:
<service
    android:name=".java.MyFirebaseMessagingService"
    android:exported="false">
    <intent-filter>
        <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
6. 代码实现
  • FirebaseManager 类
public class FirebaseManager {
    private static FirebaseManager instance = new FirebaseManager();
    
    public static FirebaseManager getInstance() {
        if (instance == null) {
            synchronized (FirebaseManager.class) {
                if (instance == null) {
                    instance = new FirebaseManager();
                }
            }
        }
        return instance;
    }

    public void init(Context context){
          // 检查 google play 服务是否可用  
          if ( isGoolgePlayServiceAvailable(context)) {
              // 检索 token 并保存
              MyFirebaseMessagingService.getToken(context);
          }

    }

     private boolean isGoolgePlayServiceAvailable(Context context, InitCallback<String> callback) {
          int resultCode =  GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(context);
          if (resultCode == ConnectionResult.SUCCESS) {
                 return true;
          }
          Log.i("device is not support google play service");
          reture false;
     }

}
  • MyFirebaseMessagingService 类
public class MyFirebaseMessagingService extends FirebaseMessagingService {

    private static String TAG = "MyFirebaseMessagingService";    

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
         // ...

        // TODO(developer): Handle FCM messages here.
          // Not getting messages here? See why this may be: https://goo.gl/39bRNJ
        Log.d(TAG, "From: " + remoteMessage.getFrom());

        // Check if message contains a data payload.
        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());

            if (/* Check if data needs to be processed by long running job */ true) {
                // For long-running tasks (10 seconds or more) use WorkManager.
                scheduleJob();
          } else {
              // Handle message within 10 seconds
              handleNow();
          }

        }

         // Check if message contains a notification payload.
        if (remoteMessage.getNotification() != null) {
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
        }

        // Also if you intend on generating your own notifications as a result of a received FCM
        // message, here is where that should be initiated. See sendNotification method below.

    }
 
    @Override
    public void onNewToken(String token) {
        Log.d(TAG, "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
       // FCM registration token to your app server.
        sendAndSaveToken(context, token);
    }

    public getToken(Context context) {
        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.i(TAG, "getToken firbase token :" + token);
                sendAndSaveToken(context, token);
        }
    });
    }
}
7. Firebase 控制台发送消息进行测试

相关文章

网友评论

      本文标题:Android 接入 firebase 推送

      本文链接:https://www.haomeiwen.com/subject/cpodtrtx.html