Learn the Firebase

2017-12-24  本文已影响75人  喜欢书的女孩
2017-12-24

一、Firebase

二、 FCM Server

  1. Firebase 云消息传递的服务器端包含两个组件:
  1. FCM 服务器协议:
FCM 服务器协议 HTTP XMPP
上行/下行消息 仅下行,即云到设备 上行和下行,即云和云到设备
消息传递 同步 异步
JSON HTTP POST 的形式 封装在 XMPP 消息中
纯文本 HTTP POST 的形式 不支持
向多个注册令牌发送多播下行消息 支持 JSON 格式的消息 不支持
  1. 基于 FCM 服务器的request
URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
return httpURLConnection;
  1. Firebase Cloud Message and Android
    一、Android 添加 SDK
    在你的 android project 根级 build.gradle 文件
buildscript {
    // ...
    dependencies {
        // ...
        classpath 'com.google.gms:google-services:3.1.0'
    }
}

在你的模块 build.gradle 文件

android {
  // ...
}

dependencies {
  // ...
  compile 'com.google.firebase:firebase-core:11.0.4'

  // Getting a "Could not find" error? Make sure you have
  // the latest Google Repository in the Android SDK manager
}

// apply plugin 必须加在底部
apply plugin: 'com.google.gms.google-services'

二、Firebase 创建应用

[1] In Firebase

Firebase-Home

[2] 转到控制台

控制台

[3] add project

project

[4] add firebase to your android app

just follow it

三、在 android 端添加接受消息的服务

总体
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {
        String refreshedToken = FirebaseInstanceId.getInstance().getToken();
        Log.d(TAG, "Refreshed token: " + refreshedToken);
        sendRegistrationToServer(refreshedToken);
    }

    /**
     * @param token The new token.
     */
    private void sendRegistrationToServer(String token) {
        // TODO: Implement this method to send token to your app server.
    }
}

5.2.2 MyFirebaseMessagingService

public class MyFirebaseMessagingService extends FirebaseMessagingService {

    @Override
    public void onMessageReceived(RemoteMessage remoteMessage) {

        Log.d(TAG, "From: " + remoteMessage.getFrom());

        if (remoteMessage.getData().size() > 0) {
            Log.d(TAG, "Message data payload: " + remoteMessage.getData());
            if (true) {
                // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
                scheduleJob();
            } else {
                // Handle message within 10 seconds
                handleNow();
            }
        }
        if (remoteMessage.getNotification() != null) {

            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
            Log.d(TAG, "Message Notification Body: " + remoteMessage.getNotification().getTitle());

  // EventBus.getDefault().post(new MessageEvent(title, content));
  //you can use eventbus to send data

        }

        //sendNotification(remoteMessage);
//you can use sendNotification to change the notification icon

    }

    private void sendNotification(RemoteMessage remoteMessage) {

//通知栏显示消息后你点击跳转的到acitivity(MyHorizontalCoordinatorNtbActivity.class)
        Intent intent = new Intent(this, MyHorizontalCoordinatorNtbActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
                PendingIntent.FLAG_ONE_SHOT);

        Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        int icon = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP ? R.drawable.app_icon: R.mipmap.app_icon;
        NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(icon)
                .setContentTitle(remoteMessage.getFrom())
                .setContentText(remoteMessage.getNotification().getBody())
                .setAutoCancel(true)
                .setSound(defaultSoundUri)
                .setContentIntent(pendingIntent);
        NotificationManager notificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
    }
    /**
     * Schedule a job using FirebaseJobDispatcher.
     */
    private void scheduleJob() {
        // [START dispatch_job]
        FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
        Job myJob = dispatcher.newJobBuilder()
                .setService(MyJobService.class)
                .setTag("my-job-tag")
                .build();
        dispatcher.schedule(myJob);
    }
    private void handleNow() {
        Log.d(TAG, "Short lived task is done.");
    }

5.2.3 MyJobService

public class MyJobService extends JobService {
    private static final String TAG = "MyJobService";

    @Override
    public boolean onStartJob(JobParameters jobParameters) {
        Log.d(TAG, "Performing long running task in scheduled job");
        // TODO(developer): add long running task here.
        return false;
    }

    @Override
    public boolean onStopJob(JobParameters jobParameters) {
        return false;
    }
}
//android:resource="@drawable/app_icon"  你可以改变图标
 <meta-data
            android:name="com.google.firebase.messaging.default_notification_icon"
            android:resource="@drawable/app_icon" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_color"
            android:resource="@color/colorAccent" />
        <meta-data
            android:name="com.google.firebase.messaging.default_notification_channel_id"
            android:value="@string/default_notification_channel_id" />

        <service
            android:name=".service.MyFirebaseMessagingService">
            <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
            </intent-filter>
        </service>
        <service
            android:name=".service.MyFirebaseInstanceIDService">
            <intent-filter>
                <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
            </intent-filter>
        </service>
        <service
            android:name=".service.MyJobService"
            android:exported="false">
            <intent-filter>
                <action android:name="com.firebase.jobdispatcher.ACTION_EXECUTE" />
            </intent-filter>
        </service>
FirebaseMessaging.getInstance().subscribeToTopic("news");

四、在 Firebase 控制端发出消息测试 android 端是否可以接收

image.png

五、在 Android 端通知栏收到消息

! 结果
上一篇 下一篇

猜你喜欢

热点阅读