如何使用 Kotlin 在 Android Jetpack Compose 中获取上下文?

How can I get context in Android Jetpack Compose using Kotlin?

我在 Kotlin 中有一个 Android Jetpack Compose 应用程序,其功能需要上下文。功能如下图

fun copyDataBase(context: Context, OUTPUT_DB_PATH: String, DB_NAME: String) {
    // Path to output database path (application database path).
    var APP_DB_FILE_PATH = OUTPUT_DB_PATH + "/" + DB_NAME

    // Path to input database file.
    var INPUT_DB_PATH = "database/" + DB_NAME

    // Open your local db as the input stream
    val databaseInput: InputStream = context.getAssets().open(INPUT_DB_PATH)

    // Open the empty db as the output stream
    val databaseOutput: OutputStream = FileOutputStream(APP_DB_FILE_PATH)

    // Transfer bytes from the inputfile to the outputfile
    val buffer = ByteArray(1024)
    var length: Int
    while (databaseInput.read(buffer).also { length = it } > 0) {
        databaseOutput.write(buffer, 0, length)
    }

    // Close the streams
    databaseOutput.flush()
    databaseOutput.close()
    databaseInput.close()
}

然后主要 activity 我这样做。

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // How can I get context to supply to the function?
        copyDataBase(context, DB_PATH, DB_NAME)

        setContent {
            Column() {
                TopAppBar(title = { Text(text = "Nyimbo") })
                ScrollableColumn(Modifier.fillMaxWidth()
                    .padding(10.dp)) {
                    lyricsPageComposable(lyricsMap = songMap)
                }
            }
        }
    }
}

如何获取上下文以将其提供给主 activity 中的函数?它是从哪个 Jetpack Compose 命名空间导入的?

我试过 import android.content.Context 但这需要初始化,我不知道该怎么做。

想法是首先将预填充的 SQLite 数据库从 assets 目录复制到应用程序中 运行。

How can I get context to supply it to the function in the main activity?

在你有那个电话的地方,使用thisActivityContext.

理想情况下,此代码不会在 activity 中 — 它会在存储库中,或者最坏情况下是在视图模型中,实际磁盘 I/O 在后台线程上执行。