如何在重复通知中显示不同的文本 Android

How to show different text in repeating notification Android

我在 viewModel(watch ListFragment) 中有一个方法 getRandomWordForNotification,它 returns 来自数据库的随机词。我想在每日通知中显示返回的单词及其翻译。有什么办法可以给AlarmReceiver传递参数吗?或者我如何将返回的单词传递到通知中并在每日 babsis 上更新它?

调用视图模型的片段:

@AndroidEntryPoint
class ListFragment : Fragment() {
    private var pendingIntent: PendingIntent? = null
    private var alarmManager: AlarmManager? = null
    private val calendar = Calendar.getInstance()

    private var _binding: FragmentListBinding? = null
    private val binding get() = _binding!!

    private val viewModel: DictionaryViewModel by activityViewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentListBinding.inflate(inflater, container, false)
        val view = binding.root
        createNotificationChannel()
        setAlarm()

        // viewModel.getRandomWordForNotification()
        return view
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }

    private fun createNotificationChannel(){
       if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O){
           val name: CharSequence = "ReminderChannel"
           val description = "Channel For Alarm Manager"
           val importance = NotificationManager.IMPORTANCE_HIGH
           val channel = NotificationChannel("channelID", name, importance)
           channel.description = description
           val notificationManager = context?.getSystemService(NotificationManager::class.java)
           notificationManager?.createNotificationChannel(channel)
       }
    }

    private fun setAlarm(){
        alarmManager = context?.getSystemService(ALARM_SERVICE) as AlarmManager
        val intent = Intent(context, AlarmReceiver::class.java)

        pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0)

        calendar[Calendar.HOUR_OF_DAY] = HOUR_FOR_NOTIFICATION
        calendar[Calendar.MINUTE] = 0
        calendar[Calendar.SECOND] = 0
        calendar[Calendar.MILLISECOND] = 0

        alarmManager!!.setRepeating(
            AlarmManager.RTC_WAKEUP,
            calendar.timeInMillis,
            AlarmManager.INTERVAL_DAY,
            pendingIntent
        )
    }
}

用于通知的 BroadcastReceiver

class AlarmReceiver(): BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val i = Intent(context, ListFragment::class.java)
        intent!!.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK // ?
        val pendingIntent = PendingIntent.getActivity(context, 0, i, 0)

        val notification = NotificationCompat.Builder(context!!, "channelID")
            .setSmallIcon(R.drawable.ic_add_notification)
            .setContentTitle("Daily Reminder")
            .setContentText("Word - Translation")
            .setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .build()

        val notificationManager = NotificationManagerCompat.from(context)
        notificationManager.notify(123, notification)
    }
}

请务必注意,您的 viewModel 和方法 getRandomWordForNotification() 将在您的视图处于活动状态时被调用。在您的情况下,当您的应用程序位于 background/killed.

时,这无法帮助您获取随机词

您应该修改您的 AlarmReceiver 以启动一个 Service,您将在其中调用您的存储库,获取新的随机词并构建您的通知。

class AlarmReceiver(): BroadcastReceiver() {
    override fun onReceive(context: Context, intent: Intent) {
        val service = Intent(context, MyRandomWordService::class.java)
        ContextCompat.startForegroundService(context, serviceIntent);
    }
}
class MyRandomWordService(name: String = "MyRandomWordService"): IntentService(name) {
    override fun onHandleIntent(intent: Intent?) {

        val notification = NotificationCompat.Builder(this.applicationContext, "channelID")
            .setSmallIcon(R.drawable.ic_add_notification)
            .setContentTitle("Daily Reminder")
            .setContentText(getRandomWordForNotification())
            .setAutoCancel(true)
            .setDefaults(NotificationCompat.DEFAULT_ALL)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .setContentIntent(pendingIntent)
            .build()

        val notificationManager = NotificationManagerCompat.from(context)
        notificationManager.notify(123, notification)
    }

    fun getRandomWordForNotification(): String {
        // your code for getting the words
    }

}

除此之外,在您的 AndroidManifest 文件中注册该服务。

<application ...>

    <service android:name=".MyRandomWordService"
    </service>

</application>

一些免责声明: