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
}

它能做什麼,不能做什麼

疑難排解