Android Fcm接入

近日公司APP需要新增海外版的App推送,需要接入FCM推送,在此做做個記錄.

首先得有一個谷歌開發者賬號,將項目與Firebase關聯,下載json文件,並放到項目指定位置,關聯參考鏈接

1.首先在項目級 build.gradle 文件中的 buildscript 和 allprojects 部分添加 Google 的 Maven 代碼庫。

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.2.0'  // Google Services plugin
  }
}

allprojects {
  // ...

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

2.在您的模塊(應用級)Gradle 文件(通常是 app/build.gradle)中,在文件末尾添加一行內容。

apply plugin: 'com.android.application'

android {
  // ...
}

// Add the following line to the bottom of the file:
apply plugin: 'com.google.gms.google-services'  // Google Play services Gradle plugin

3.將 Firebase SDK 添加到您的應用.

在您的模塊(應用級)Gradle 文件(通常是 app/build.gradle)中,添加核心 Firebase SDK 的依賴項:

dependencies {
 // ...
 implementation 'com.google.firebase:firebase-core:17.0.0'

 // Getting a "Could not find" error? Make sure that you've added
 // Google's Maven repository to your root-level build.gradle file
}

2.設置 Firebase 和 FCM SDK

將 Android 版雲消息傳遞庫的依賴項添加到您的模塊(應用級)Gradle 文件(通常爲 app/build.gradle

implementation 'com.google.firebase:firebase-messaging:20.0.0'

新建一個FcmMessagService繼承 FirebaseMessagingService


/**
 * create by 
 * on 2020/4/27
 * explain${Fcm接收通知}
 */
public class FcmMessagService extends FirebaseMessagingService {
    public static String TAG = "tag_-----FcmMessagService:";

    @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.e(TAG, "From Id為: " + 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.

//        if (remoteMessage.getNotification() != null && remoteMessage.getNotification().getBody() != null) {
//            sendNotification(getApplicationContext(), remoteMessage.getNotification().getTitle(), remoteMessage.getNotification().getBody());
//        } else {
//            sendNotification(getApplicationContext(), remoteMessage.getData().get("title"),remoteMessage.getData().get("body"));
//        }
    }


    @Override
    public void onDeletedMessages() {
        super.onDeletedMessages();
    }

    @Override
    public void onMessageSent(String s) {
        super.onMessageSent(s);
    }

    @Override
    public void onSendError(String s, Exception e) {
        super.onSendError(s, e);
    }

    private void sendNotification(Context iContext, String messageTitle, String messageBody) {
        NotificationManager notificationManager = (NotificationManager) iContext.getSystemService(Context.NOTIFICATION_SERVICE);
//        Intent intent = new Intent(this, MessageActivity.class); // 接收到通知後,點擊通知,啓動 MessageActivity

//        PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long[] pattern = {500, 500, 500, 500, 500};
        NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), "-1")
                .setTicker(messageTitle)
                .setSmallIcon(R.mipmap.able_icon)
                .setContentTitle("push 通知 標題")
                .setAutoCancel(true)
                .setContentText(messageBody)
                .setWhen(System.currentTimeMillis())
                .setVibrate(pattern)
                .setLights(Color.BLUE, 1, 1);
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND | NotificationCompat.DEFAULT_VIBRATE);

//        builder.setContentIntent(pendingIntent);
//        builder.setFullScreenIntent(pendingIntent, true);//將一個Notification變成懸掛式Notification

        if (notificationManager != null) {
            notificationManager.notify(0, builder.build());
        }
    }
}

在AndroidManifest.xml添加服務:

 <service
            android:name=".FcmMessagService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <!-- Set custom default icon. This is used when no icon is set for incoming notification messages.
     See README(https://goo.gl/l4GJaQ) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@mipmap/xxx_icon" />
        <!-- Set color used with incoming notification messages. This is used when no color is set for the incoming
             notification message. See README(https://goo.gl/6BKBk7) for more. -->
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />

在需要的地方獲取令牌,設備要有Google Play服務才行,

//檢查是否安裝了GooglePlay,安裝了則設置token,未安裝則不設置,默認為空
            FirebaseInstanceId.getInstance().getInstanceId()
                    .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
                        @Override
                        public void onComplete(@NonNull Task<InstanceIdResult> task) {
                            if (!task.isSuccessful()) {
                                Log.e("TAG", "getInstanceId failed", task.getException());
                                return;
                            }
                            // Get new Instance ID token
                            InstanceIdResult result = task.getResult();
                            if (result != null) {
                                String token = result.getToken();
                                //保存FCM token
                                ABLESharedPreferencesUtils.setFcmToken(xxx.this, token);
                            }
                        }
                    });

然後在平臺上推送測試推送,正常接收即可,

App在前臺推送:

App在後臺推送:

官方參考(需翻牆)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章