我构建了一个待办事项列表应用程序,该应用程序应该显示通知以提醒任务。为了能够将通知安排在截止日期的准确时间,我将通知数据从 flutter 传递到 kotlin,并显示来自广播接收器的通知。
这里我将通知数据发送到 kotlin:
await platform.invokeMethod('setNextNotification', {
'tasksNames': tasksNames,
'notificationsTimeInMillis': notificationsTimeInMillis
});
Run Code Online (Sandbox Code Playgroud)
这就是我在 FlutterActivity 中获取数据的方式:
private const val CHANNEL = "flutter.native/helper"
class MainActivity : FlutterActivity() {
companion object {
const val TASKS_NAMES_EXTRA = "tasksNames"
const val NOTIFICATIONS_TIME_IN_MILLIS_EXTRA = "notificationsTimeInMillis"
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
// Init the AlarmManager.
val alarmManager = getSystemService(Context.ALARM_SERVICE) as AlarmManager
// We got here from the setNotifications() method in flutter...
MethodChannel(flutterView, CHANNEL).setMethodCallHandler { call, result ->
if (call.method == "setNextNotification") {
// Get the time till next notification
val notificationsTimeInMillis: ArrayList<Long> = call.argument(NOTIFICATIONS_TIME_IN_MILLIS_EXTRA)
?: ArrayList()
// Create a pending intent for the notifications
val pIntent: PendingIntent? = createPendingIntent(call.argument(TASKS_NAMES_EXTRA), call.argument(TIME_LEFT_TEXTS_EXTRA), notificationsTimeInMillis, this)
// Cancel all alarms
while (alarmManager.nextAlarmClock != null)
alarmManager.cancel(alarmManager.nextAlarmClock.showIntent)
// Set the alarm
setAlarm(notificationsTimeInMillis[0], pIntent, alarmManager)
}
}
}
private fun setAlarm(notificationTime: Long, pIntent: PendingIntent?, alarmManager: AlarmManager) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // The API is 23 or higher...
alarmManager.setAlarmClock(AlarmManager.AlarmClockInfo(notificationTime, pIntent), pIntent)
} else { // The API is 19 - 22...
// We want the alarm to go of on the exact time it scheduled for so we use the setExact method.
alarmManager.setExact(AlarmManager.RTC_WAKEUP, notificationTime, pIntent)
}
}
private fun createPendingIntent(tasksNames: ArrayList<String>?, timeTillNotificationsInMillis: ArrayList<Long>?,
context: Context): android.app.PendingIntent? {
return try {
val intent: android.content.Intent = android.content.Intent(context, AlarmManagerHelperWakeful::class.java)
intent.action = "notification"
intent.putStringArrayListExtra(TASKS_NAMES_EXTRA, tasksNames)
intent.putStringArrayListExtra(NOTIFICATIONS_TIME_IN_MILLIS_EXTRA, timeTillNotificationsInMillisAsString)
android.app.PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
} catch (e: java.lang.Exception) {
null
}
}
Run Code Online (Sandbox Code Playgroud)
}
这就是我在 BroadcastReceiver 上显示通知的方式,然后设置下一个通知:
Class AlarmManagerHelperWakeful : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (intent != null && intent.action == "notification" && context != null) {
val tasksLabels: ArrayList<String> = intent.getStringArrayListExtra(MainActivity.TASKS_NAMES_EXTRA)
?: ArrayList()
val notificationsTimeInMillisAsString: ArrayList<String> = intent.getStringArrayListExtra(MainActivity.NOTIFICATIONS_TIME_IN_MILLIS_EXTRA)
?: ArrayList()
if (tasksLabels.size > 0) {
// Create a notification manager.
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var builder = NotificationCompat.Builder(context) // The initialization is for api 25 or lower so it is deprecated.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { // This is API 26 or higher...
// Create a channel for API 26 or higher;
val channelId = "channel_01" // The id of the channel.
if (notificationManager.getNotificationChannel(channelId) == null) {
val channel = NotificationChannel(channelId,
context.getString(R.string.notification_channel_name),
NotificationManager.IMPORTANCE_DEFAULT)
notificationManager.createNotificationChannel(channel)
}
// Update the builder to a no deprecated one.
builder = NotificationCompat.Builder(context, channelId)
}
// Set the notification details.
builder.setSmallIcon(android.R.drawable.ic_notification_overlay)
builder.setContentTitle(tasksLabels[0])
builder.setContentText(someText)
builder.priority = NotificationCompat.PRIORITY_DEFAULT
notificationId = someUniqueId
// Show the notification.
notificationManager.notify(notificationId.toInt(), builder.build())
// Remove this notification from the notifications lists.
tasksLabels.removeAt(0)
notificationsTimeInMillisAsString.removeAt(0)
// There are more notifications...
if (tasksLabels.size > 0) {
// Init the AlarmManager.
val alarmManager = context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
// Cancel all alarms
while (alarmManager.nextAlarmClock != null)
alarmManager.cancel(alarmManager.nextAlarmClock.showIntent)
// Create a pending intent for the notifications
val pIntent: PendingIntent? = createPendingIntent(tasksLabels, cnotificationsTimeInMillisAsString, context)
// Set the alarm
setAlarm(notificationsTimeInMillisAsString[0].toLong(), pIntent, alarmManager)
}
}
} else {
if (intent == null) {
Log.d("Debug", "Checking: intent == null")
} else if ( intent.action != "notification") {
Log.d("Debug", "Checking: intent.action != notification")
val tasksLabels: ArrayList<String> = intent.getStringArrayListExtra(MainActivity.TASKS_NAMES_EXTRA)
?: ArrayList()
Log.d("Debug", "Checking: tasksNames.size inside else if" + tasksLabels.size)
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
除非我重新启动设备,否则一切都工作得很好。然后广播接收者得到一个没有任何数据的意图。为了让 BoradcastReceiver 获取通知数据的意图,我需要从 flutter 代码调用该方法(将通知数据发送到 kotlin 代码的方法),这意味着目前用户必须为此输入应用程序。否则,用户在进入我的应用程序并重新调用颤振代码之前不会看到通知。
我怎样才能克服这个问题?
您应该使用推送通知,而不是向广播接收器发送本地通知。有很多情况会导致您的应用无法发送本地通知。例如:用户关闭应用程序(很多用户总是在使用后关闭应用程序)、操作系统关闭应用程序或清理内存、Dart 方法崩溃。Firebase FCM 非常简单,它比使用广播接收器的解决方案简单得多。也完全免费。
https://pub.dev/packages/firebase_messaging
Pushwoosh也不错,有日程通知
https://pub.dev/packages/pushwoosh
使用推送通知还有其他优点,您的应用程序也可以在 iOS 上运行,不需要让您的应用程序在后台运行,如果您的应用程序没有任何需要在后台运行的特殊功能(音乐播放器),那么这是一个非常糟糕的主意、地理位置、VOIP)
如果您不想使用推送通知。看看这个库: https: //pub.dev/packages/flutter_local_notifications
| 归档时间: |
|
| 查看次数: |
1683 次 |
| 最近记录: |