Synchronize with Firebase

同步 Firebase

This lesson teaches you to

这节课您将学会

  1. Initialize Firebase Realtime Database

  2. 初始化 Firebase 实时数据库

  3. Write data into a shared database

  4. 写入数据到一个共享数据库

Try it out

试一试

A smart doorbell should publish the captured events and images to the cloud to allow other clients to connect and display the data, or to enable further analysis.

智能门铃应该将拍照事件和图像发布到云端,以便允许其他客户端进行连接并显示门铃数据,或者进行进一步的分析。

In this lesson, you will use Firebase Realtime Database to persist and publish events that are consumed by a mobile companion app.

本节课中,您将使用 Firebase 实时数据库保存和发布配套应用所使用的门铃事件。

Add Firebase to your project

在您的工程中添加 Firebase 支持


To enable Firebase Realtime Database for your project:

为了让您的工程支持 Firebase 实时数据库:

  1. Install the Firebase Android SDK into your app project.

  2. 在您的工程中安装 Firebase Android SDK

  3. In the Firebase console, select Import Google Project to import the Google Cloud project you created for Cloud Vision into Firebase.

  4. Firebase 控制台 选择 Import Google Project 来将您为 Cloud Vision 创建的 Google Cloud 工程导入 Firebase 中。

  5. Download and install the google-services.json file as described in the instructions.

  6. 按说明下载并安装 google-services.json 文件。

  7. Add the Firebase Realtime Database dependency to your app-level build.gradle file:

  8. 在您应用的 build.gradle 文件中添加 Firebase 实时数据库依赖:

    1. dependencies {
    2. ...
    3. compile 'com.google.firebase:firebase-core:9.4.0'
    4. compile 'com.google.firebase:firebase-database:9.4.0'
    5. }

Configure database rules

配置数据库规则


You need to specify who can read and write to your Firebase Realtime Database. To configure your Firebase database access rules:

您需要指定谁可以读和写您的 Firebase 实时数据库。使用下面的规则来配置您的数据库:

  1. In the Firebase console, on the page for your project, click Database.

  2. Firebase 控制台 ,在您的工程页,点击 Database

  3. Click Rules, and update the database rules to allow public read/write access:

  4. 点击 Rules ,然后更新数据库规则,让所有人拥有读写权限:

    1. {
    2. "rules": {
    3. ".read": true,
    4. ".write": true
    5. }
    6. }
  5. Click Publish.

  6. 点击 发布

For more information on setting database rules, see Getting Started with Database Rules.

更多设置数据库规则的信息,请查看 数据库规则入门指南

Write captured data to database

将拍摄数据写入到数据库


Upon each doorbell event, the app captures the following pieces of data and stores them in Firebase:

应用将会获得如下一系列数据并将他们存入 Firebase 数据库中:

  • Camera image data
  • 相机图像数据
  • Event timestamp
  • 事件发生时的时间戳
  • Cloud Vision annotations
  • Cloud Vision 标注

The following JSON schema describes how the data is organized in Firebase for each event:

下面的 JSON 样式描述了每次事件数据在 Firebase 中的存储格式:

  1. <doorbell-entry> {
  2. "image": <Base64 image data>,
  3. "timestamp": <event timestamp>,
  4. "annotations": {
  5. <label>: <score>,
  6. <label>: <score>,
  7. ...
  8. }
  9. }

To write the captured data into a Firebase database:

将拍摄的数据存入 Firebase 数据库中:

  1. Initialize an instance of the database with FirebaseDatabase.getInstance():

  2. 使用 FirebaseDatabase.getInstance() 初始化一个数据库实例:

    1. import com.google.firebase.database.FirebaseDatabase;
    2. ...
    3. public class DoorbellActivity extends Activity {
    4. ...
    5. private FirebaseDatabase mDatabase;
    6. @Override
    7. protected void onCreate(Bundle savedInstanceState) {
    8. super.onCreate(savedInstanceState);
    9. ...
    10. mDatabase = FirebaseDatabase.getInstance();
    11. }
    12. }
  1. Write the captured image data, timestamp, and Cloud Vision annotations to a new DatabaseReference in the database.

  2. 使用一个新的 DatabaseReference 将拍摄的图像数据、时间戳以及 Cloud Vision 标注写入数据库。

    1. import com.google.firebase.database.DatabaseReference;
    2. import com.google.firebase.database.FirebaseDatabase;
    3. import com.google.firebase.database.ServerValue;
    4. ...
    5. public class DoorbellActivity extends Activity {
    6. ...
    7. private FirebaseDatabase mDatabase;
    8. private void onPictureTaken(final byte[] imageBytes) {
    9. if (imageBytes != null) {
    10. final DatabaseReference log = mDatabase.getReference("logs").push();
    11. String imageStr = Base64.encodeToString(imageBytes, Base64.NO_WRAP | Base64.URL_SAFE);
    12. // upload image to firebase
    13. log.child("timestamp").setValue(ServerValue.TIMESTAMP);
    14. log.child("image").setValue(imageStr);
    15. mCloudHandler.post(new Runnable() {
    16. @Override
    17. public void run() {
    18. Log.d(TAG, "sending image to cloud vision");
    19. // annotate image by uploading to Cloud Vision API
    20. try {
    21. Map<String, Float> annotations = CloudVisionUtils.annotateImage(imageBytes);
    22. Log.d(TAG, "cloud vision annotations:" + annotations);
    23. if (annotations != null) {
    24. log.child("annotations").setValue(annotations);
    25. }
    26. } catch (IOException e) {
    27. Log.e(TAG, "Cloud Vison API error: ", e);
    28. }
    29. }
    30. });
    31. }
    32. }
    33. }

Note: The push() method creates a new node referenced by a unique key.

注意:push() 方法将会根据唯一的键值创建一个新的节点。

Your app will now write each captured image and the associated image analysis to a Firebase database! Go ahead and try it with the sample code.

您的应用将每次拍摄的图像和对应的图像标记数据写入到 Firebase 数据库中!接下来,继续尝试使用示例代码。

Verify the synchronized data

验证同步的数据


Firebase automatically synchronizes changes to the local database with the cloud. To verify that the data your app wrote was synchronized:

Firebase 会自动将更改同步到本地数据库中。下面来验证您的应用已经被自动同步:

  1. In the Firebase console, on the page for your project, click Database.

  2. Firebase 控制台,在您工程中,点击 Database

  3. Click Data.

  4. 点击 Data

  5. Observe that a new entry was created under the “logs” node.

  6. 您会看到在 “logs” 节点中,有一条新记录被创建。