微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter AlarmManager not working with flutter_nearby_connections 插件说:PlatformException lateinit 属性活动尚未初始化,

如何解决Flutter AlarmManager not working with flutter_nearby_connections 插件说:PlatformException lateinit 属性活动尚未初始化,

我正在后台服务回调函数调用 Flutter 附近的连接插件代码,以便我可以在后台检测附近的设备它不起作用,因为 Flutter 的附近连接插件需要活动上下文。如何在回调中提供?如果我在后台服务的回调中调用 nearconnection 构造函数,它会显示活动是 null。如果我从 background_fetchalarm_manager 等任何 Flutter 插件后台函数调用附近的设备代码,它不起作用,它表示 kotlin 属性活动未在 Flutter_nearby_connections 插件中初始化。但是我必须在后台调用代码如何从回调的颤动代码中提供活动上下文?如果没有后台服务,附近的设备工​​作得很好,但是当它与后台功能一起使用时,它不起作用,说活动是 null。如何解决这个问题?

import 'dart:isolate';
import 'dart:math';
import 'package:Flutter/material.dart';
import 'package:android_alarm_manager_plus/android_alarm_manager_plus.dart';
import 'package:Flutter_nearby_connections/Flutter_nearby_connections.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  bool test = await AndroidAlarmManager.initialize();
  runApp(NearbyPlease());
}

class NearbyPlease extends StatefulWidget {
  const NearbyPlease({Key? key}) : super(key: key);

  @override
  _NearbyPleaseState createState() => _NearbyPleaseState();
}

class _NearbyPleaseState extends State<NearbyPlease> {
  NearbyService nearbyService = NearbyService();
  @override
  void initState() {
    // Todo: implement initState
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(body: Center(child: RaisedButton(onpressed: () async {
      //this function nearbydevice will run after every one minute in background even
      // the app is closed
      await AndroidAlarmManager.periodic(
          const Duration(seconds: 60),101,printHello);
    }))));
  }

  static Future<void> printHello() async {
    try {
      NearbyService nearbyService = NearbyService();
      await nearbyService.init(
          callback: (running) async {
            nearbyService.startAdvertisingPeer();
            await nearbyService.startbrowsingForPeers();
          },serviceType: 'mpconn',strategy: Strategy.P2P_CLUSTER,deviceName: Random().nextInt(9).toString());
    } catch (e) {
      print(e);
    }
  }
}


pubspec.yaml

description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots,like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in Flutter
# build by specifying --build-name and --build-number,respectively.
# In Android,build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS,build-name is used as CFBundleShortVersionString while build-number used as CFBundLeversion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  Flutter:
    sdk: Flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  android_alarm_manager_plus: ^1.0.1
  Flutter_nearby_connections:



dev_dependencies:
  Flutter_test:
    sdk: Flutter

# For @R_333_4045@ion on the generic Dart part of this file,see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
Flutter:

  # The following line ensures that the Material Icons font is
  # included with your application,so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  

错误日志:

Syncing files to device CPH1937...
I/e.alarm_manage(16947): ProcessprofilingInfo new_methods=431 is saved saved_to_disk=1 resolve_classes_delay=5000
I/FlutterBackgroundExecutor(16947): Starting AlarmService...
I/AndroidAlarmManagerPlugin(16947): onAttachedToEngine
I/AlarmService(16947): AlarmService started!
D/SurfaceView(16947): 27843277 setAlpha: mUseAlpha = false alpha=1.0
D/SurfaceView(16947): 27843277 updateSurfaceAlpha: setUseAlpha() is not called,ignored.
D/ColorViewRootUtil(16947): swipeFromBottom!
D/ColorViewRootUtil(16947): nav bar mode ignore false downX 370 downY 794 mScreenHeight 1600 mScreenWidth 720 mStatusBarHeight 36 globalScale 1.125 nav mode 0 rotation 0 event MotionEvent { action=ACTION_DOWN,actionButton=0,id[0]=0,x[0]=370.0,y[0]=794.0,toolType[0]=TOOL_TYPE_FINGER,buttonState=0,classification=NONE,MetaState=0,flags=0x2,edgeFlags=0x0,pointerCount=1,historySize=0,eventTime=12896264,downTime=12896264,deviceid=5,source=0x1002,displayId=0 }
D/ColorViewRootUtil(16947): swipeFromBottom!
D/ColorViewRootUtil(16947): swipeFromBottom!
E/MethodChannel#Flutter_nearby_connections(16947): Failed to handle method call
E/MethodChannel#Flutter_nearby_connections(16947): kotlin.UninitializedPropertyAccessException: lateinit property activity has not been initialized
E/MethodChannel#Flutter_nearby_connections(16947):  at com.nankai.Flutter_nearby_connections.FlutterNearbyConnectionsPlugin.onMethodCall(FlutterNearbyConnectionsPlugin.kt:77)
E/MethodChannel#Flutter_nearby_connections(16947):  at io.Flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/MethodChannel#Flutter_nearby_connections(16947):  at io.Flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#Flutter_nearby_connections(16947):  at io.Flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/MethodChannel#Flutter_nearby_connections(16947):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#Flutter_nearby_connections(16947):  at android.os.MessageQueue.next(MessageQueue.java:336)
E/MethodChannel#Flutter_nearby_connections(16947):  at android.os.Looper.loop(Looper.java:184)
E/MethodChannel#Flutter_nearby_connections(16947):  at android.app.ActivityThread.main(ActivityThread.java:7864)
E/MethodChannel#Flutter_nearby_connections(16947):  at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#Flutter_nearby_connections(16947):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/MethodChannel#Flutter_nearby_connections(16947):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:998)
E/Flutter (16947): [ERROR:Flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: PlatformException(error,lateinit property activity has not been initialized,null,kotlin.UninitializedPropertyAccessException: lateinit property activity has not been initialized
E/Flutter (16947):  at com.nankai.Flutter_nearby_connections.FlutterNearbyConnectionsPlugin.onMethodCall(FlutterNearbyConnectionsPlugin.kt:77)
E/Flutter (16947):  at io.Flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:233)
E/Flutter (16947):  at io.Flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/Flutter (16947):  at io.Flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:818)
E/Flutter (16947):  at android.os.MessageQueue.nativePollOnce(Native Method)
E/Flutter (16947):  at android.os.MessageQueue.next(MessageQueue.java:336)
E/Flutter (16947):  at android.os.Looper.loop(Looper.java:184)
E/Flutter (16947):  at android.app.ActivityThread.main(ActivityThread.java:7864)
E/Flutter (16947):  at java.lang.reflect.Method.invoke(Native Method)
E/Flutter (16947):  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/Flutter (16947):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:998)
E/Flutter (16947): )
E/Flutter (16947): #0      StandardMethodCodec.decodeEnvelope (package:Flutter/src/services/message_codecs.dart:597:7)
E/Flutter (16947): #1      MethodChannel._invokeMethod (package:Flutter/src/services/platform_channel.dart:158:18)
E/Flutter (16947): <asynchronous suspension>

有谁知道如何解决这个问题,以便我可以在后台检测附近的设备?我已经使用 foreground_service Flutter 插件background_fetch Flutter 插件尝试了相同的代码,但得到相同的异常。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。