工具集#04 Firebase

工具集#04 Firebase_第1张图片
2017-12-24

一、Firebase

  • AdWords
  • 统计分析(Analytics)
  • 崩溃报告(Crash Reporting)
  • 数据库 —— 用于存储 JSON 数据的 NoSQL 数据库
  • 动态链接(Dynamic Links) —— 将用户带至应用内预期页面的深度链接(deep links)
  • 托管(Hosting) —— 针对 Web 应用的全球 CDN
  • 索引(Indexing) —— 对应用进行索引,用于谷歌搜索
  • 邀请(Invites) —— 支持用户与其他用户分享有关应用的信息
  • 消息(Messaging) —— 即此前的 Google Cloud Messaging,后来被重新命名为 Firebase Cloud Messaging
  • 通知(Notifications) —— 管理发给用户的通知
  • 离线(Offline) —— 支持应用在本地缓存中存储数据,这样可以在离线时保持运行
  • 实时(Real Time) —— 数据实时保存至云数据库
  • 远程配置(Remote Config) —— 支持开发者在不要求用户下载新版本 app 的情况下,修改应用的行为和外观。该特性用于修改应用的视觉主题,满足不同用户群组的需求,运行 A/B 测试等。
  • 存储(Storage) —— 存储用户的语音、图片和视频
  • 同步(Synchronization) —— 当设备上的数据变动时,将会推送至 Firebase,然后再推回到所有相关联的设备。另外,离线后重新在线使用时,设备将自动更新至最近的快照
  • 测试实验室(Test Lab) —— 在真实设备上测试应用

二、 FCM Server

  1. Firebase 云消息传递的服务器端包含两个组件:
  • 由 Google 提供的 FCM服务器
  • 应用服务器或其他受信任的环境(服务器--》FCM服务器--》用户设备)
  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

工具集#04 Firebase_第2张图片
Firebase-Home

[2] 转到控制台

工具集#04 Firebase_第3张图片
控制台

[3] add project

工具集#04 Firebase_第4张图片
project

[4] add firebase to your android app

工具集#04 Firebase_第5张图片
just follow it

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

工具集#04 Firebase_第6张图片
总体
  • 第一步:把 google-services.json 拷贝 黏贴到 app 包下.
  • 第二步:写三个 Service
    5.2.1 MyFirebaseInstanceIDService
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;
    }
}
  • 第三步: AndroidManifest
//android:resource="@drawable/app_icon"  你可以改变图标
 
        
        

        
            
                
            
        
        
            
                
            
        
        
            
                
            
        
  • 第四步:Activity
    可以订阅 eventbus 从service 传过来的数据,并显示出来.
    可以订阅消息主题
FirebaseMessaging.getInstance().subscribeToTopic("news");

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

工具集#04 Firebase_第7张图片
image.png

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

!
工具集#04 Firebase_第8张图片
结果

你可能感兴趣的:(工具集#04 Firebase)