Meteor-Android-DDP通信 - 简书

来源: Meteor-Android-DDP通信 – 简书

版本要求

配置

  • 将需要的包加入项目
    • 在根目录下的build.gradle里加如下两段代码
      • 申明Gradle仓库地址
        allprojects {
          repositories {
              maven { url "https://jitpack.io" }
          }
        }
      • 申明Gradle的依赖
        dependencies {
          compile 'com.github.delight-im:Android-DDP:v3.1.2'
        }
  • AndroidManifest.xml 中添加许可:
     <uses-permission android:name="android.permission.INTERNET" />

使用

  • 创建DDP client实例
    public class MyActivity extends Activity implements MeteorCallback {
    
        private Meteor mMeteor;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // 创建一个实例
            mMeteor = new Meteor(this, "ws://example.meteor.com/websocket");
    
            // 注册回调函数
            mMeteor.addCallback(this);
    
            // 建立连接
            mMeteor.connect();
        }
    
        public void onConnect(boolean signedInAutomatically) { }
    
        public void onDisconnect() { }
    
        public void onDataAdded(String collectionName, String documentID, String newValuesJson) {
            // 自行解析json数据 (不推荐)
            // 或者
            // 直接用数据库语句操作 (后面会有详细介绍) (推荐)
        }
    
        public void onDataChanged(String collectionName, String documentID, String updatedValuesJson, String removedValuesJson) {
            // 自行解析json数据 (不推荐)
            // 或者
            // 直接用数据库语句操作 (后面会有详细介绍) (推荐)
        }
    
        public void onDataRemoved(String collectionName, String documentID) {
            // 自行解析json数据 (不推荐)
            // 或者
            // 直接用数据库语句操作 (后面会有详细介绍) (推荐)
        }
    
        public void onException(Exception e) { }
    
        @Override
        public void onDestroy() {
            mMeteor.disconnect();
            mMeteor.removeCallback(this);
            // or
            // mMeteor.removeCallbacks();
    
            // ...
    
            super.onDestroy();
        }
    
    }
  • 单例模式
    • 在一开始就创建一个实例
      MeteorSingleton.createInstance(this, "ws://example.meteor.com/websocket")
      // 代替
      // new Meteor(this, "ws://example.meteor.com/websocket")
    • 实例可以直接用 (通过 Activity 实例)
      MeteorSingleton.getInstance()
      // 代替
      // mMeteor
    • 所有API方法都可以通过MeteorSingleton.getInstance() 调用。
  • 注册一个回调函数
    // MeteorCallback callback;
    mMeteor.addCallback(callback);
  • 取消一个回调函数
    mMeteor.removeCallbacks();
    // or
    // // MeteorCallback callback;
    // mMeteor.removeCallback(callback);
  • 向 collection 中添加数据
    Map<String, Object> values = new HashMap<String, Object>();
    values.put("_id", "my-id");
    values.put("some-key", "some-value");
    
    mMeteor.insert("my-collection", values);
    // or
    // mMeteor.insert("my-collection", values, new ResultListener() { });
  • 更新 collection 中的数据
    Map<String, Object> query = new HashMap<String, Object>();
    query.put("_id", "my-id");
    
    Map<String, Object> values = new HashMap<String, Object>();
    values.put("some-key", "some-value");
    
    mMeteor.update("my-collection", query, values);
    // or
    // mMeteor.update("my-collection", query, values, options);
    // or
    // mMeteor.update("my-collection", query, values, options, new ResultListener() { });
  • 删除 collection 中的数据
    mMeteor.remove("my-collection", "my-id");
    // or
    // mMeteor.remove("my-collection", "my-id", new ResultListener() { });
  • 从后端订阅数据
    String subscriptionId = mMeteor.subscribe("my-subscription");
    // or
    // String subscriptionId = mMeteor.subscribe("my-subscription", new Object[] { arg1, arg2 });
    // or
    // String subscriptionId = mMeteor.subscribe("my-subscription", new Object[] { arg1, arg2 }, new SubscribeListener() { });
  • 取消订阅
    mMeteor.unsubscribe(subscriptionId);
    // or
    // mMeteor.unsubscribe(subscriptionId, new UnsubscribeListener() { });
  • 调用后端自定义的方法
    mMeteor.call("myMethod");
    // or
    // mMeteor.call("myMethod", new Object[] { arg1, arg2 });
    // or
    // mMeteor.call("myMethod", new ResultListener() { });
    // or
    // mMeteor.call("myMethod", new Object[] { arg1, arg2 }, new ResultListener() { });
  • 与后端断开连接
    mMeteor.disconnect();
  • 创建新账户 (后端依赖包 accounts-password)
    mMeteor.registerAndLogin("john", "john.doe@example.com", "password", new ResultListener() { });
    // or
    // mMeteor.registerAndLogin("john", "john.doe@example.com", "password", profile, new ResultListener() { });
  • 通过 username 登录 (依赖后端包 accounts-password)
    mMeteor.loginWithUsername("john", "password", new ResultListener() { });
  • 通过邮箱登录 (依赖后端包 accounts-password)
    mMeteor.loginWithEmail("john.doe@example.com", "password", new ResultListener() { });
  • 检查是否已经登录 (依赖后端包 accounts-password)
    mMeteor.isLoggedIn();
  • 获取 user ID (前提是已登录) (依赖后端包 accounts-password)
    mMeteor.getUserId();
  • 登出 (依赖后端包 accounts-password)
    mMeteor.logout();
    // or
    // mMeteor.logout(new ResultListener() { });
  • 检查客户端是否连接
    mMeteor.isConnected();
  • 手动重连 (一般不需要)
    mMeteor.reconnect();

利用数据库语句处理数据

配置数据库

InMemoryDatabaseDatabase 实例的唯一子类,代码如下:

mMeteor = new Meteor(this, "ws://example.meteor.com/websocket", new InMemoryDatabase());

此时,所有数据都自动从后端接收,并解析完成存入数据库。不需要手动解析JSON!

接收数据时,注意一些状态, onDataAdded, onDataChanged or onDataRemoved

访问数据库

Database database = mMeteor.getDatabase();

这些和后续的方法,都支持链式调用。

通过集合名从数据库获取集合

// String collectionName = "myCollection";
Collection collection = mMeteor.getDatabase().getCollection(collectionName);

获取数据库中所有的集合名字

String[] collectionNames = mMeteor.getDatabase().getCollectionNames();

获取数据库中集合数量

int numCollections = mMeteor.getDatabase().count();

通过ID从集合中取数据

// String documentId = "wjQvNQ6sGjzLMDyiJ";
Document document = mMeteor.getDatabase().getCollection(collectionName).getDocument(documentId);

获取集合中所有数据的ID

String[] documentIds = mMeteor.getDatabase().getCollection(collectionName).getDocumentIds();

获取集合中数据数量

int numDocuments = mMeteor.getDatabase().getCollection(collectionName).count();

在集合中查找数据

以下所有方法都支持链式调用,并随意组合。

// String fieldName = "age";
// int fieldValue = 62;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereEqual(fieldName, fieldValue);
// String fieldName = "active";
// int fieldValue = false;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNotEqual(fieldName, fieldValue);
// String fieldName = "accountBalance";
// float fieldValue = 100000.00f;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereLessThan(fieldName, fieldValue);
// String fieldName = "numChildren";
// long fieldValue = 3L;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereLessThanOrEqual(fieldName, fieldValue);
// String fieldName = "revenue";
// double fieldValue = 0.00;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereGreaterThan(fieldName, fieldValue);
// String fieldName = "age";
// int fieldValue = 21;
Query query = mMeteor.getDatabase().getCollection(collectionName).whereGreaterThanOrEqual(fieldName, fieldValue);
// String fieldName = "address";
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNull(fieldName);
// String fieldName = "modifiedAt";
Query query = mMeteor.getDatabase().getCollection(collectionName).whereNotNull(fieldName);
Document[] documents = mMeteor.getDatabase().getCollection(collectionName).find();
// int limit = 30;
Document[] documents = mMeteor.getDatabase().getCollection(collectionName).find(limit);
// int limit = 30;
// int offset = 5;
Document[] documents = mMeteor.getDatabase().getCollection(collectionName).find(limit, offset);
Document document = mMeteor.getDatabase().getCollection(collectionName).findOne();

可以组合到一起,如下:

Document document = mMeteor.getDatabase().getCollection("users").whereNotNull("lastLoginAt").whereGreaterThan("level", 3).findOne();

通过属性名查找属性

// String fieldName = "age";
Object field = mMeteor.getDatabase().getCollection(collectionName).getDocument(documentId).getField(fieldName);

获取所有属性名

String[] fieldNames = mMeteor.getDatabase().getCollection(collectionName).getDocument(documentId).getFieldNames();

获取属性数量

int numFields = mMeteor.getDatabase().getCollection(collectionName).getDocument(documentId).count();
赞(0) 打赏
分享到: 更多 (0)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏