Android 实时调试

无需重启应用即可实时编辑 Android 应用数据库

向您的应用添加一个仅用于调试的小型辅助程序,并在应用持续运行的同时通过浏览器编辑其 SQLite 数据库。

打开查看器

您将获得什么

实时编辑的工作方式类似于 Android Studio 的 Database Inspector,但在浏览器中进行。SQLite Viewer 会将每次更改发送到您调试应用内的一个小型 ContentProvider,由它在应用自己的数据库上执行。应用保持运行,无需停止、复制或重启任何东西。

仅限调试版本。该辅助程序允许任何拥有 USB 调试权限的人在数据库上执行写入语句,因此请只在 src/debug 中注册它,切勿将其包含在发布版本中。

设置步骤

  1. 添加辅助类。将 SqliteViewerProvider.kt(或下方代码)下载或复制到您的应用模块中,例如 app/src/main/java/com/example/debughelper/。将 package 行修改为与文件夹一致。
  2. 仅为调试版本注册。创建 app/src/debug/AndroidManifest.xml,并添加下方的 provider 条目。由于它位于 debug 源集中,发布版本永远不会包含该条目,也不会暴露任何内容。
  3. 可选:刷新 Room 界面。Room 只会注意到通过它自己的连接所做的更改。请设置一次 afterWrite 钩子,让使用 LiveData 和 Flow 的界面在实时编辑后立即更新。
  4. 运行调试版本。将调试版本安装到手机上,并打开一次应用,以便 Android 注册该 provider。
  5. 开启实时编辑。在 SQLite Viewer 中选择 Android,连接手机,打开应用数据库并勾选实时编辑。此时会出现绿色的实时编辑徽章。从现在起,您执行的每一次行编辑、插入、删除和 SQL 语句也会应用到正在运行的应用。

调试清单

<?xml version="1.0" encoding="utf-8"?>
<!-- src/debug/AndroidManifest.xml  (debug builds only) -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <application>
        <provider
            android:name="com.example.debughelper.SqliteViewerProvider"
            android:authorities="${applicationId}.sqliteviewer"
            android:exported="true" />
    </application>
</manifest>

可选的 Room 钩子

// In your Application class (optional, only if you use Room LiveData / Flow)
override fun onCreate() {
    super.onCreate()
    if (BuildConfig.DEBUG) {
        SqliteViewerProvider.afterWrite = {
            AppDatabase.getInstance(this).invalidationTracker.refreshVersionsAsync()
        }
    }
}

辅助程序 (SqliteViewerProvider.kt)

package com.example.debughelper // use any package, for example your app's own

import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.net.Uri
import android.os.Bundle
import android.util.Base64
import org.json.JSONArray

/**
 * DEBUG BUILDS ONLY.
 *
 * Lets SQLite Viewer (https://sqliteviewer.codemasterlk.com) edit this app's databases
 * while the app keeps running. The class can live in src/main, but it is only registered
 * in src/debug/AndroidManifest.xml, so release builds never expose it.
 */
class SqliteViewerProvider : ContentProvider() {

    companion object {
        /** Optional: called after every successful live edit, e.g. to refresh Room observers. */
        @JvmStatic
        var afterWrite: (() -> Unit)? = null

        private val allowedStatement = Regex("""^(INSERT|UPDATE|DELETE|REPLACE|CREATE|DROP|ALTER)\b""", RegexOption.IGNORE_CASE)
        private val leadingNoise = Regex("""^(\s|--[^\n]*\n|/\*.*?\*/)*""", RegexOption.DOT_MATCHES_ALL)
        private val safeName = Regex("""^[A-Za-z0-9._-]+$""")
    }

    private val handles = HashMap<String, SQLiteDatabase>()

    override fun onCreate(): Boolean = true

    override fun call(method: String, arg: String?, extras: Bundle?): Bundle {
        val answer = try {
            when (method) {
                "ping" -> "OK:1"
                "batch" -> "OK:" + runBatch(extras?.getString("db"), arg)
                else -> "ERR:unknown method $method"
            }
        } catch (e: Throwable) {
            "ERR:" + (e.message ?: e.javaClass.simpleName).replace('\n', ' ')
        }
        return Bundle().apply { putString("r", answer) }
    }

    @Synchronized
    private fun database(name: String): SQLiteDatabase {
        handles[name]?.let { if (it.isOpen) return it }

        val file = context!!.getDatabasePath(name)
        require(file.exists()) { "database not found: $name" }

        return SQLiteDatabase.openDatabase(file.path, null, SQLiteDatabase.OPEN_READWRITE)
            .also { handles[name] = it }
    }

    private fun runBatch(name: String?, base64: String?): Int {
        require(name != null && safeName.matches(name)) { "invalid database name" }
        require(!base64.isNullOrEmpty()) { "no statements" }

        val statements = JSONArray(String(Base64.decode(base64, Base64.DEFAULT), Charsets.UTF_8))
        val db = database(name)

        db.beginTransaction()
        try {
            for (i in 0 until statements.length()) {
                val sql = statements.getString(i)
                require(allowedStatement.containsMatchIn(sql.replaceFirst(leadingNoise, ""))) {
                    "statement type not allowed"
                }
                db.execSQL(sql)
            }
            db.setTransactionSuccessful()
        } finally {
            db.endTransaction()
        }

        afterWrite?.invoke()
        return statements.length()
    }

    // Not used: the viewer talks to this provider only through call().
    override fun query(uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String?): Cursor? = null
    override fun getType(uri: Uri): String? = null
    override fun insert(uri: Uri, values: ContentValues?): Uri? = null
    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int = 0
    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>?): Int = 0
}

它能做什么,不能做什么

故障排除