gpt4 book ai didi

flutter - 重新启动设备后在flutter中调用方法

转载 作者:行者123 更新时间:2023-12-03 02:48:03 27 4
gpt4 key购买 nike

我构建了一个待办事项列表应用程序,该应用程序应显示提醒任务的通知。为了能够将通知安排到截止日期的确切时间,我将通知数据从 flutter 传递到Kotlin,并显示来自广播接收器的通知。
在这里,我将通知数据发送给kotlin:

 await platform.invokeMethod('setNextNotification', {
'tasksNames': tasksNames,
'notificationsTimeInMillis': notificationsTimeInMillis
});
这就是我在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
}
}
}
这就是我在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)
}
}

}
}
除非我重新启动设备,否则一切正常。然后,广播接收器得到了没有任何数据的意图。为了让BoradcastReceiver能够接收通知数据,我需要从flutter代码中调用该方法(将通知数据发送到kotlin代码的方法),这意味着现在用户必须为此输入应用程序。否则,用户只有进入我的应用程序并重新调用 flutter 代码,才能看到通知。
我该如何克服这个问题?

最佳答案

您应该使用“推送通知”,而不是将本地通知发送到广播接收器。在很多情况下,您的应用无法发送本地通知。例如:用户关闭了应用程序(使用后用户总是关闭应用程序),操作系统关闭了应用程序或清除了内存,Dart方法崩溃了。
Firebase FCM非常简单,比使用广播接收器的解决方案简单得多。也完全免费。
https://pub.dev/packages/firebase_messaging
Pushwoosh也很好,它有时间表通知
https://pub.dev/packages/pushwoosh
使用推送通知还具有其他优点,即您的应用程序也可以在iOS上运行,不需要让您的应用程序在后台运行,如果您的应用程序没有任何需要在后台运行的特殊功能(音乐播放器),则是个坏主意,地理位置,VOIP)
如果您不想使用推送通知。看一下这个库:
https://pub.dev/packages/flutter_local_notifications

关于flutter - 重新启动设备后在flutter中调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63419221/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com