CV工程师
2024-07-22 06:15:59 阅读:150
在 Jetpack Compose 中使用 Room 和 Service 进行数据库交互是完全可行的。下面是一个示例,演示如何在 Service 中使用 Room 数据库,并通过 Jetpack Compose 来展示数据。
首先,我们需要创建一个 Room 数据库。假设我们有一个简单的 User 实体。
// User.kt
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "user_table")
data class User(
@PrimaryKey(autoGenerate = true) val id: Int = 0,
val name: String
)
然后,创建一个 DAO 接口。
// UserDao.kt
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
@Dao
interface UserDao {
@Insert
suspend fun insert(user: User)
@Query("SELECT * FROM user_table")
suspend fun getAllUsers(): List<User>
}
接着,创建数据库类。
// AppDatabase.kt
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
@Database(entities = [User::class], version = 1, exportSchema = false)
abstract class AppDatabase : RoomDatabase() {
abstract fun userDao(): UserDao
companion object {
@Volatile
private var INSTANCE: AppDatabase? = null
fun getDatabase(context: Context): AppDatabase {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
AppDatabase::class.java,
"app_database"
).build()
INSTANCE = instance
instance
}
}
}
}
接下来,我们创建一个 Service 来进行数据库操作。
// UserService.kt
import android.app.Service
import android.content.Intent
import android.os.IBinder
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
class UserService : Service() {
private lateinit var database: AppDatabase
private val serviceScope = CoroutineScope(Job() + Dispatchers.IO)
override fun onCreate() {
super.onCreate()
database = AppDatabase.getDatabase(this)
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
val action = intent?.getStringExtra("ACTION")
when (action) {
"INSERT" -> {
val name = intent.getStringExtra("NAME") ?: return START_NOT_STICKY
insertUser(name)
}
}
return START_NOT_STICKY
}
private fun insertUser(name: String) {
serviceScope.launch {
val user = User(name = name)
database.userDao().insert(user)
}
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
}
最后,我们使用 Jetpack Compose 来展示从数据库中读取的数据。
// MainActivity.kt
import android.content.Intent
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch
class MainActivity : ComponentActivity() {
private lateinit var database: AppDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
database = AppDatabase.getDatabase(this)
setContent {
MyApp()
}
lifecycleScope.launch {
database.userDao().insert(User(name = "John Doe"))
}
}
@Composable
fun MyApp() {
var users by remember { mutableStateOf(listOf<User>()) }
LaunchedEffect(Unit) {
users = database.userDao().getAllUsers()
}
MaterialTheme {
Surface(modifier = Modifier.fillMaxSize()) {
Column {
Button(onClick = {
startService(Intent(this@MainActivity, UserService::class.java).apply {
putExtra("ACTION", "INSERT")
putExtra("NAME", "Jane Doe")
})
}) {
Text(text = "Add User")
}
LazyColumn {
items(users) { user ->
Text(text = user.name)
}
}
}
}
}
}
}
评论
扫描二维码获取文章详情
更多精彩内容尽在:WWW.ZNGG.NET