【问题标题】:Invoke a method in flutter after restarting the device重启设备后调用flutter中的方法
【发布时间】:2020-08-24 05:35:13
【问题描述】:

我构建了一个待办事项列表应用程序,它应该显示通知以提醒任务。为了能够将通知安排到截止日期的确切时间,我将通知数据从 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 获得通知数据的意图,我需要从颤振代码中调用该方法(将通知数据发送到 kotlin 代码的方法),这意味着目前,用户必须为此输入应用程序。否则,用户在进入我的应用并重新调用颤振代码之前不会看到通知。

我该如何克服这个问题?

【问题讨论】:

  • 你可以参考这篇文章获得更多想法medium.com/flutter/…
  • @JitenBasnet 有很多代码需要消化。但据我了解,我从 Flutter 调用 Kotlin 中的一个方法,然后使用回调从 Kotlin 接收数据到 dart。问题是,回调在用户重启设备后是否保持活动状态,或者关闭设备会杀死回调,因此我无法在设备打开时将数据发送回 dart。
  • 我在这里也收集了一些资料。 stackoverflow.com/questions/63228013/…

标签: flutter dart


【解决方案1】:

您应该使用推送通知而不是向广播接收器发送本地通知。有很多情况使您的应用无法发送本地通知。例如:用户关闭应用程序(很多用户在使用后总是关闭应用程序),操作系统关闭应用程序或清理内存,Dart 方法崩溃。 Firebase FCM 非常简单,它比使用广播接收器的解决方案简单得多。也完全免费。

https://pub.dev/packages/firebase_messaging

Pushwoosh 也不错,有日程通知

https://pub.dev/packages/pushwoosh

使用推送通知还有其他优点,您的应用程序也可以在 iOS 上运行,不需要让您的应用程序在后台运行,如果您的应用程序没有任何需要在后台运行的特殊功能,这是非常糟糕的主意(音乐播放器、地理位置、VOIP)

如果您不想使用推送通知。看看这个库: https://pub.dev/packages/flutter_local_notifications

【讨论】:

  • 您好,谢谢您的回答。我正在为 IOS 使用颤振本地通知,但在 android 上,通知的传递是不准确的,这使得它对 android 毫无用处。我阅读了 firebase 消息传递文档,但找不到如何从应用程序内安排任务提醒的通知。有什么解释我该怎么做吗?
【解决方案2】:

现在您正在将数据从 dart 发送到本机插件。你可以反过来试试。 This 示例显示了如何获取本机 android 重启事件。接下来,您可以使用this 示例来获取所需的数据。获取数据后,您可以设置通知。

您也可以尝试将最后一个通知的信息存储在 SharedPreferences 中,在启动时获取该信息,然后设置通知。

【讨论】:

  • 我知道如何监听重启事件。发生这种情况时,我需要知道如何在颤振中调用方法。您的第二个链接中的示例不是那么清楚。我应该把 myUtilsHandler 方法放在哪里?如何在java中初始化通道对象? Java代码里面还有代码吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-29
相关资源
最近更新 更多