后台调用中出现颤振的本地通知初始化错误

问题描述

我正在尝试创建一个通过workmanager插件调度的后台服务来触发简单通知的应用程序。这个想法是每15分钟检查一次mqtt实例中的任何消息,并在代理上有任何消息可用的情况下显示一个简单的本地通知。该通知也在应用程序初始化时被调用。主要问题是,无论我终止应用程序多少次并重新启动它,通知都可以正常运行,但是一旦我尝试调度后台服务,该服务就可以正常运行,但是本地通知插件无法初始化。

代码:

import 'dart:async';

import 'package:workmanager/workmanager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

import './mqttClientWrapper.dart';

const mqtt_task_key = "MqttTask";

Future callbackDispatcher() async {
    Workmanager.executeTask((taskName,inputData) async {
        if (taskName == mqtt_task_key) {
            print("running instance in background");
            print("instantiating");
            await RandomState().setup();

        }
        return Future.value(true);
    });
}

class Random extends StatefulWidget {
    @override
    RandomState createState() => RandomState();

}

class RandomState extends State {
    MQTTClientWrapper mqttClientWrapper;

    String message = "";

    Future setup() async {
        FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
        mqttClientWrapper = MQTTClientWrapper(() => {},(newMessage) => gotNewMessage(newMessage,flutterLocalNotificationsPlugin));
        print('1');
        mqttClientWrapper.prepareMqttClient();
        print('2');

        var initializationSettingsAndroid =
            new AndroidInitializationSettings('@mipmap/ic_launcher');
        print('3');
        var initializationSettingsIOS = new IOSInitializationSettings();
        var initializationSettings = new InitializationSettings(
            initializationSettingsAndroid,initializationSettingsIOS);
        //flutterLocalNotificationsPlugin = new FlutterLocalNotificationsPlugin();
        await flutterLocalNotificationsPlugin.initialize(initializationSettings,onSelectNotification: onSelectNotification);
    }

    Future gotNewMessage(String newMessage,flutterLocalNotificationsPlugin) async {
        setState(() {
            this.message = newMessage;
        });
        await _showNotificationWithDefaultSound(flutterLocalNotificationsPlugin);
        print('test');
    }

    @override
    void initState() {
        super.initState();
        setup();
        Workmanager.cancelAll();
    }

    @override
    Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
                title: Text('random'),),body: Center(
                child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,children: [
                        Text(
                            message,style: Theme.of(context).textTheme.headline4,FlatButton(
                            color: Colors.blue,onPressed: () {
                                Workmanager.initialize(
                                    callbackDispatcher,isInDebugMode: true,);
                                print("initialized");
                                Workmanager.registerPeriodicTask('1',mqtt_task_key,frequency: Duration(minutes: 15),initialDelay: Duration(seconds: 30));
                            },)
                    ],);
    }

    Future onSelectNotification(String payload) async {
        showDialog(
            context: context,builder: (_) {
                return new AlertDialog(
                    title: Text("PayLoad"),content: Text("Payload : $payload"),);
            },);
    }

    Future _showNotificationWithDefaultSound(flutterLocalNotificationsPlugin) async {
        var androidPlatformChannelSpecifics = new AndroidNotificationDetails(
            'your channel id','your channel name','your channel description',importance: Importance.Max,priority: Priority.High);
        var iOSPlatformChannelSpecifics = new IOSNotificationDetails();
        var platformChannelSpecifics = new NotificationDetails(
            androidPlatformChannelSpecifics,iOSPlatformChannelSpecifics);
        await flutterLocalNotificationsPlugin.show(
            0,'New Post','New Message',platformChannelSpecifics,payload: 'Default_Sound',);
    }
}

控制台日志

I/flutter (16424): 1
I/flutter (16424): MQTTClientWrapper::test client connecting....
I/flutter (16424): 2020-08-19 04:01:10.452967 -- Authenticating with username '{wbynzcri}' and password '{uOIqIxMgf3Dl}'
I/flutter (16424): 2020-08-19 04:01:10.489029 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter (16424): 2020-08-19 04:01:10.489300 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0
I/flutter (16424): 2020-08-19 04:01:10.489672 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter (16424): 2
I/flutter (16424): 3
I/flutter (16424): 2020-08-19 04:01:11.724721 -- MqttServerConnection::_startListening
I/flutter (16424): 2020-08-19 04:01:11.742755 -- SynchronousMqttServerConnectionHandler::internalConnect - connection complete
I/flutter (16424): 2020-08-19 04:01:11.743072 -- SynchronousMqttServerConnectionHandler::internalConnect sending connect message
I/flutter (16424): 2020-08-19 04:01:11.748088 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.connect
I/flutter (16424): Header: MessageType = MqttMessageType.connect,Duplicate = false,Retain = false,Qos = MqttQos.atMostOnce,Size = 0
I/flutter (16424): Connect Variable Header: ProtocolName=MQIsdp,ProtocolVersion=3,ConnectFlags=Connect Flags: Reserved1=false,CleanStart=true,WillFlag=false,WillQos=MqttQos.atMostOnce,WillRetain=false,PasswordFlag=true,UserNameFlag=true,KeepAlive=60
I/flutter (16424): MqttConnectPayload - client identifier is : #
I/flutter (16424): 2020-08-19 04:01:11.780464 -- SynchronousMqttServerConnectionHandler::internalConnect - pre sleep,state = Connection status is connecting with return code of noneSpecified and a disconnection origin of none
I/flutter (16424): 2020-08-19 04:01:12.118299 -- MqttConnection::_onData
I/flutter (16424): 2020-08-19 04:01:12.137902 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.connectAck
I/flutter (16424): Header: MessageType = MqttMessageType.connectAck,Size = 2
I/flutter (16424): Connect Variable Header: TopicNameCompressionResponse={0},ReturnCode={MqttConnectReturnCode.connectionAccepted}
I/flutter (16424): 2020-08-19 04:01:12.144405 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:12.153670 -- SynchronousMqttServerConnectionHandler::_connectAckProcessor
I/flutter (16424): 2020-08-19 04:01:12.154185 -- SynchronousMqttServerConnectionHandler::_connectAckProcessor - state = connected
I/flutter (16424): MQTTClientWrapper::OnConnected client callback - Client connection was sucessful
I/flutter (16424): 2020-08-19 04:01:12.156048 -- SynchronousMqttServerConnectionHandler:: cancelling connect timer
I/flutter (16424): 2020-08-19 04:01:12.158088 -- SynchronousMqttServerConnectionHandler::internalConnect - post sleep,state = Connection status is connected with return code of connectionAccepted and a disconnection origin of none
I/flutter (16424): 2020-08-19 04:01:12.158600 -- SynchronousMqttServerConnectionHandler::internalConnect exited with state Connection status is connected with return code of connectionAccepted and a disconnection origin of none
I/flutter (16424): MQTTClientWrapper::Mosquitto client connected
I/flutter (16424): MQTTClientWrapper::Subscribing to the 4060431/# topic
I/flutter (16424): 2020-08-19 04:01:12.177163 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.subscribe
I/flutter (16424): Header: MessageType = MqttMessageType.subscribe,Qos = MqttQos.atLeastOnce,Size = 0
I/flutter (16424): Subscribe Variable Header: MessageIdentifier={1}
I/flutter (16424): Payload: Subscription [{1}]
I/flutter (16424): {{ Topic={4060431/#},Qos={MqttQos.atMostOnce} }}
I/flutter (16424):
I/flutter (16424): 2020-08-19 04:01:12.492990 -- MqttConnection::_onData
I/flutter (16424): 2020-08-19 04:01:12.500615 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.subscribeAck
I/flutter (16424): Header: MessageType = MqttMessageType.subscribeAck,Size = 3
I/flutter (16424): SubscribeAck Variable Header: MessageIdentifier={1}
I/flutter (16424): Payload: Qos grants [{1}]
I/flutter (16424): {{ Grant={MqttQos.atMostOnce} }}
I/flutter (16424):
I/flutter (16424): 2020-08-19 04:01:12.501061 -- MqttServerConnection::_onData - message processed
I/flutter (16424): MQTTClientWrapper::Subscription confirmed for topic 4060431/#
I/flutter (16424): 2020-08-19 04:01:12.897098 -- MqttConnection::_onData
I/flutter (16424): 2020-08-19 04:01:12.920910 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.publish
I/flutter (16424): Header: MessageType = MqttMessageType.publish,Retain = true,Size = 19
I/flutter (16424): Publish Variable Header: TopicName={4060431/offline/},MessageIdentifier={0},VH Length={18}
I/flutter (16424): Payload: {1 bytes={<49>
I/flutter (16424): 2020-08-19 04:01:12.921398 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:12.923384 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.publish
I/flutter (16424): Header: MessageType = MqttMessageType.publish,Size = 45
I/flutter (16424): Publish Variable Header: TopicName={4060431/information/codename/},VH Length={31}
I/flutter (16424): Payload: {14 bytes={<83><77><82><84><65><76><82><84><49><66><50><76><49><71>
I/flutter (16424): 2020-08-19 04:01:12.924024 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:12.926510 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.publish
I/flutter (16424): Header: MessageType = MqttMessageType.publish,Size = 33
I/flutter (16424): Publish Variable Header: TopicName={4060431/information/version/},VH Length={30}
I/flutter (16424): Payload: {3 bytes={<48><46><49>
I/flutter (16424): 2020-08-19 04:01:12.926893 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:12.928255 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.publish
I/flutter (16424): Header: MessageType = MqttMessageType.publish,Size = 27
I/flutter (16424): Publish Variable Header: TopicName={4060431/sensor/0/type/},VH Length={24}
I/flutter (16424): Payload: {3 bytes={<71><65><83>
I/flutter (16424): 2020-08-19 04:01:12.928666 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:12.929900 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.publish
I/flutter (16424): Header: MessageType = MqttMessageType.publish,Size = 26
I/flutter (16424): Publish Variable Header: TopicName={4060431/sensor/0/state/},VH Length={25}
I/flutter (16424): Payload: {1 bytes={<49>
I/flutter (16424): 2020-08-19 04:01:12.930394 -- MqttServerConnection::_onData - message processed
I/flutter (16424): MQTTClientWrapper::GOT A NEW MESSAGE 1
I/flutter (16424): MQTTClientWrapper::GOT A NEW MESSAGE SMRTALRT1B2L1G
I/flutter (16424): MQTTClientWrapper::GOT A NEW MESSAGE 0.1
I/flutter (16424): MQTTClientWrapper::GOT A NEW MESSAGE GAS
I/flutter (16424): MQTTClientWrapper::GOT A NEW MESSAGE 1
I/flutter (16424): test
I/flutter (16424): test
I/flutter (16424): test
I/flutter (16424): test
I/flutter (16424): test
I/art (16424): Do partial code cache collection,code=21KB,data=30KB
I/art (16424): After code cache collection,data=30KB
I/art (16424): Increasing code cache capacity to 128KB
I/flutter (16424): initialized
I/flutter (16424): 2020-08-19 04:01:30.486502 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.pingRequest
I/flutter (16424): Header: MessageType = MqttMessageType.pingRequest,Size = 0
I/flutter (16424): 2020-08-19 04:01:30.807658 -- MqttConnection::_onData
I/flutter (16424): 2020-08-19 04:01:30.811320 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.pingResponse
I/flutter (16424): Header: MessageType = MqttMessageType.pingResponse,Size = 0
I/flutter (16424): 2020-08-19 04:01:30.812317 -- MqttServerConnection::_onData - message processed
I/flutter (16424): 2020-08-19 04:01:50.502517 -- MqttConnectionHandlerBase::sendMessage - MQTTMessage of type MqttMessageType.pingRequest
I/flutter (16424): Header: MessageType = MqttMessageType.pingRequest,Size = 0
I/flutter (16424): 2020-08-19 04:01:50.833619 -- MqttConnection::_onData
I/flutter (16424): 2020-08-19 04:01:50.834847 -- MqttServerConnection::_onData - message received MQTTMessage of type MqttMessageType.pingResponse
I/flutter (16424): Header: MessageType = MqttMessageType.pingResponse,Size = 0
I/flutter (16424): 2020-08-19 04:01:50.835866 -- MqttServerConnection::_onData - message processed
I/flutter (16424): running instance in background
I/flutter (16424): instantiating
I/flutter (16424): 1
I/flutter (16424): MQTTClientWrapper::test client connecting....
I/flutter (16424): 2020-08-19 04:01:53.864177 -- Authenticating with username '{wbynzcri}' and password '{uOIqIxMgf3Dl}'
I/flutter (16424): 2020-08-19 04:01:53.918924 -- SynchronousMqttServerConnectionHandler::internalConnect entered
I/flutter (16424): 2020-08-19 04:01:53.919223 -- SynchronousMqttServerConnectionHandler::internalConnect - initiating connection try 0
I/flutter (16424): 2020-08-19 04:01:53.919650 -- SynchronousMqttServerConnectionHandler::internalConnect - insecure TCP selected
I/flutter (16424): 2
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Intent android.app.Activity.getIntent()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.initialize(FlutterLocalNotificationsPlugin.java:856)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:742)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at android.os.MessageQueue.next(MessageQueue.java:323)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at android.os.Looper.loop(Looper.java:136)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at android.app.ActivityThread.main(ActivityThread.java:6165)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:888)
E/MethodChannel#dexterous.com/flutter/local_notifications(16424): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:778)
I/WM-WorkerWrapper(16424): Worker result FAILURE for Work [ id=9519d0f6-1acd-445d-a325-8281ae5dd445,tags={ be.tramckrijte.workmanager.BackgroundWorker } ]

请注意,一旦启动了后台任务,初始化的命令就会打印在控制台上,并且实际执行任务与命令之间会有30秒的延迟,这就是为什么您会在它们之间看到mqtt实例消息。

主要问题开始于表单方法调用。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)