拆分 sqlite 文件以进行同步

Splitting sqlite files for syncing

我正在编写一个 Android 应用程序,它从传感器收集数据并将其存储在本地 SQLite 数据库中。

我想做的是将此数据(读取:上传)与后端应用程序同步(为此我正在使用 Android 的同步适配器)。

由于在同步过程中可以获取数据,我认为将sqlite文件的最大大小设置为700 Kb是合理的(无所谓),因此同步适配器将同步这700 Kb 文件(通过 POST 请求),不包括活动文件。一旦 sqlite 文件达到限制,我将创建一个新的活动 sqlite 数据库并写入它。

如何实现?或许,有更好的解决办法?

  • 最终我决定只使用一个带有 'synced_at' 字段的数据库文件。
  • 我还使用 WAL 在将新数据写入数据库时​​读取数据(要同步)。
  • MySQLiteHelper class 是使用单例模式实现的,因此在我的例子中,您可以从 Main activity 和 Sync 适配器同时访问您的数据库。
  • 我还在将数据发送到服务器之前将其压缩(对于文本,我使用 gzip 实现了 5 倍的压缩)。

数据点:

@AllArgsConstructor
@NoArgsConstructor
@Builder
@Getter
@Setter
public class Data {
    private long id;
    private float a;
    private float b;
    private float c;
    private long timestamp;
    private long synced_at;
}

MySQLiteHelper:

public class MySQLiteHelper extends SQLiteOpenHelper {

    private static MySQLiteHelper sInstance;

    public static final String DB_NAME = "db.sqlite";
    public static final int DB_VERSION = 1;
    public static final String TABLE_NAME = "data";

    public static synchronized MySQLiteHelper getInstance(Context context) {
        if (sInstance == null) {
            sInstance = new MySQLiteHelper(context.getApplicationContext());
        }
        return sInstance;
    }

    private MySQLiteHelper(Context context) {
        super(context, context.getExternalFilesDir(null).getAbsolutePath() + "/" + DB_NAME,
                null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase) {
        String createDbSql = "...";
        sqLiteDatabase.execSQL(createDbSql);
        Log.d("log", "db created");
    }

    @Override
    public void onOpen(SQLiteDatabase db) {
        super.onOpen(db);
        Log.d("log", "db opened");
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
        Log.d("log", "db upgraded");
    }
}