Flutter AlarmManager not working with flutter_nearby_connections plugin says: PlatformException lateinit property activity has not been initialized,

Viewed 164

I am calling flutter nearby connection plugin code in background service call back function so I can detect nearby devices in background it does not work because nearby connection plugin of flutter requires context of activity. How to provide that in call back? If I am calling nearbyconnection constructor in callback of background service it says activity is null. If I am calling nearby devices code from background function of any flutter plugin like background_fetch or alarm_manager it does not work it says kotlin property activity is not initialized in flutter_nearby_connections plugin. But I have to call that code in background how can I give activity context from flutter code of callback? Without background service nearby devices is working perfectly fine but when using it with background function it doesn't work saying activity is null. How to resolve this?

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 information 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

  

Error logs:

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>

Anyone knows how to resolve this so I can detect nearby devices in background?I have tried same code with foreground_service flutter plugin and background_fetch plugin of flutter but getting same exception.

0 Answers
Related