question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

FlutterJNI detached from native C++

See original GitHub issue

Hi,

First i would like to appreciate the effort put into developing this plugin and also the patience to respond to users issues. You guys are the best!

I am building a safety app that sends location updates when the phone is shook and that needs to work even while the app is in background.

I tried to use the flutter shake sensor plugin to trigger the location update when the phone is shook but whenever the app goes into background, i get the message:

W/FlutterJNI(27552): Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: plugins.flutter.io/sensors/accelerometer. Response ID: 0

i would appreciate any help 🙏

My full code:

import 'dart:async';
import 'dart:isolate';

import 'dart:ui';

import 'package:flutter/material.dart';

import 'package:background_locator/background_locator.dart';
import 'package:background_locator/location_dto.dart';
import 'package:background_locator/location_settings.dart';
import 'package:shake/shake.dart';
import 'package:sentry/sentry.dart';
import 'package:trackamsos/background/SOSHandler.dart';
import 'package:trackamsos/background/ensureAlwaysBackground.dart';
import 'package:trackamsos/core/helpers/getShakeThresholdGravity.dart';

class BackgroundService {
  static final BackgroundService _backgroundService =
      BackgroundService._internal();
  static const String _isolateName = "LocatorIsolate";
  static final SOSHandler sosHandler = SOSHandler();
  static final ReceivePort port = ReceivePort();
  final SentryClient sentry = SentryClient(
      dsn:
          'https://XXXXXXXXXXXXXXXXXXXXX.ingest.sentry.io/xxxx');
  static ShakeDetector shakeDetector;

  factory BackgroundService() => _backgroundService;

  Future<void> start() async {
    if (await isRunning()) {
      return;
    }
    
    if (IsolateNameServer.lookupPortByName(_isolateName) != null) {
      IsolateNameServer.removePortNameMapping(_isolateName);
    }

    IsolateNameServer.registerPortWithName(port.sendPort, _isolateName);

    await _initPlatformState();

    await ensureAlwaysBackground ();

    _startSOSListener();

    await _startLocationService();
  }

  void stop() async {
    if (!await isRunning()) {
      return;
    }

    _stopSOSListener();

    if (IsolateNameServer.lookupPortByName(_isolateName) != null) {
      IsolateNameServer.removePortNameMapping(_isolateName);
    }

    BackgroundLocator.unRegisterLocationUpdate();
  }

  Future<bool> isRunning() =>
      BackgroundLocator.isRegisterLocationUpdate() /*_isRunning*/;

  void updateShakeThreshold() => _startShakeListener();

  static Future<void> _startSOSListener() async {
    _startShakeListener();
    _startPowerButtonListener();
  }

  static void _stopSOSListener() {
    _stopShakeListener();
    _stopPowerButtonListener();
  }

  static Future<void> _startShakeListener() async {
    if (shakeDetector != null) {
      _stopShakeListener();
    }

    try {
      shakeDetector = ShakeDetector.autoStart(
          shakeThresholdGravity: getShakeThresholdGravity(),
          onPhoneShake: () => sosHandler.run());
    } catch (error, stackTrace) {
      try {
        await _backgroundService.sentry.captureException(
          exception: error,
          stackTrace: stackTrace,
        );
      } catch (error) {
        print(error);
      }
    }
  }

  static void _startPowerButtonListener() {
  }

  static void
      _stopPowerButtonListener() => null;

  static void _stopShakeListener() => shakeDetector?.stopListening();

  Future<void> _startLocationService() =>
      BackgroundLocator.registerLocationUpdate(
        locationCallback,
        //optional
        initCallback: _initCallback,
        disposeCallback: _disposeCallback,
        androidNotificationCallback: _notificationCallback,
        settings: LocationSettings(
          //Scroll down to see the different options
          notificationMsg: "Tap to Open App",
          notificationIcon: '@drawable/ic_notification',
          notificationTitle: "TrackAm SOS Activated",
          notificationIconColor: Colors.redAccent,
          notificationChannelName: 'TrackAm SOS',
          wakeLockTime: 60,
          autoStop: false,
          interval: 1,
          distanceFilter: 1000,
          accuracy: LocationAccuracy.POWERSAVE,
        ),
      ).whenComplete(_disposeCallback);

  static void _initCallback(Map<String, dynamic> args) => _startSOSListener();

  static void _disposeCallback() => _stopSOSListener();

  static void locationCallback(LocationDto locationDto) {
    final SendPort send = IsolateNameServer.lookupPortByName(_isolateName);
    send?.send(locationDto);
  }

  static void _notificationCallback() {
    print('User clicked on the notification');
  }

  Future<void> _initPlatformState() => BackgroundLocator.initialize();
  
  BackgroundService._internal();
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
uzenith360commented, Aug 1, 2020

I later discovered the real issue was that the background locator callbacks need to be in the root of lib folder. I’m not sure that was pointed out anywhere in documentation.

Maybe it should be added as a note in documentation incase someone else faces this issue.

Ofcourse, i could do a pr

@mehdok @gpibarra

0reactions
mehdokcommented, Aug 17, 2020

It seems that the issue is solved, I’m closing the issue but feel free to open it anytime;

Read more comments on GitHub >

github_iconTop Results From Across the Web

"Tried to send a platform message to Flutter, but FlutterJNI was ...
The same thing happens with location: "Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not...
Read more >
FlutterJNI was detached from native C++ · Issue #1504 - GitHub
When the app reopens from a state change Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++...
Read more >
Resolving FlutterJNI not attached to native — Flutter Android ...
Navigate to the android directory which holds your project's generated Android code. Then head to app > src > main and finally open...
Read more >
FlutterJNI - Flutter - Dart API docs
Second, every JNI call must be registered in C/C++ code and this registration ... Attaches this FlutterJNI instance to Flutter's native engine, which...
Read more >
Tried to send a platform message to Flutter, but FlutterJNI was ...
[Solved]-"Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++." After start a background service and closes the...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found