要在Android Studio中从SQLite数据库发送通知,你需要遵循以下步骤:
dependencies {
implementation 'androidx.core:core-ktx:1.5.0'
implementation 'androidx.appcompat:appcompat:1.3.1'
implementation 'com.google.android.material:material:1.4.0'
implementation 'androidx.room:room-runtime:2.3.0'
annotationProcessor 'androidx.room:room-compiler:2.3.0'
}
@Entity(tableName = "notifications")
data class NotificationEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
val title: String,
val message: String
)
@Dao
interface NotificationDao {
@Query("SELECT * FROM notifications")
fun getAllNotifications(): List
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertNotification(notification: NotificationEntity)
}
@Database(entities = [NotificationEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun notificationDao(): NotificationDao
}
class AppApplication : Application() {
companion object {
lateinit var database: AppDatabase
private set
}
override fun onCreate() {
super.onCreate()
database = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java,
"app_database"
).build()
}
}
val notifications = AppApplication.database.notificationDao().getAllNotifications()
for (notification in notifications) {
val notificationBuilder = NotificationCompat.Builder(this, "channel_id")
.setContentTitle(notification.title)
.setContentText(notification.message)
.setSmallIcon(R.drawable.notification_icon)
.setAutoCancel(true)
val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.notify(notification.id, notificationBuilder.build())
}
确保在AndroidManifest.xml文件中配置通知渠道:
...
...
以上是从SQLite数据库发送通知的解决方法,希望对你有所帮助!
上一篇:Android Studio - 从EditText视图获取输入
下一篇:Android Studio - 从SQLite数据库加载RecyclerView,在EditText中输入一个单词。