Baseflow / flutter-geolocator

Android and iOS Geolocation plugin for Flutter
https://baseflow.com/
MIT License
1.25k stars 659 forks source link

[Bug]: Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: flutter.baseflow.com/geolocator_updates_android. #1382

Open gujjar1988 opened 1 year ago

gujjar1988 commented 1 year ago

Please check the following before submitting a new issue.

Please select affected platform(s)

Steps to reproduce

I want location updates in app terminated state

Expected results

location streaming on app terminated state

Actual results

Tried to send a platform message to Flutter, but FlutterJNI was detached from native C++. Could not send. Channel: flutter.baseflow.com/geolocator_updates_android.

Code sample

Code sample ```dart locationSettings = AndroidSettings( accuracy: LocationAccuracy.high, // distanceFilter: 3, forceLocationManager: true, intervalDuration: const Duration(seconds: 1), //(Optional) Set foreground notification config to keep the app alive //when going to the background foregroundNotificationConfig: const ForegroundNotificationConfig( notificationText: "App will continue to receive your location even when you are in Background.", notificationTitle: "Running in Background", notificationIcon: AndroidResource(name: 'ic_launcher', defType: 'mipmap'), enableWakeLock: true, enableWifiLock: true, setOngoing: true ) ); positionStream = Geolocator.getPositionStream(locationSettings: locationSettings).listen( (Position? position) { if (position?.isValid ?? false) { this.position = position!; position.saveLocation(); } if (kDebugMode) print(position?.toJson()); }); ```

Screenshots or video

Screenshots or video demonstration [Upload media here]

Version

10.1.0

Flutter Doctor output

Doctor output ```console [✓] Flutter (Channel stable, 3.13.9, on macOS 14.1.1 23B81 darwin-arm64, locale en-IN) • Flutter version 3.13.9 on channel stable at /Users/pankaj/Desktop/development/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision d211f42860 (4 weeks ago), 2023-10-25 13:42:25 -0700 • Engine revision 0545f8705d • Dart version 3.1.5 • DevTools version 2.25.0 [✓] Android toolchain - develop for Android devices (Android SDK version 34.0.0) • Android SDK at /Users/pankaj/Library/Android/sdk • Platform android-34, build-tools 34.0.0 • ANDROID_HOME = /Users/pankaj/Library/Android/sdk • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231) • All Android licenses accepted. [✓] Xcode - develop for iOS and macOS (Xcode 15.0.1) • Xcode at /Applications/Xcode.app/Contents/Developer • Build 15A507 • CocoaPods version 1.14.3 [✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome [✓] Android Studio (version 2022.3) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b829.9-10027231) [✓] Connected device (3 available) • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64 • Android 14 (API 34) (emulator) • macOS (desktop) • macos • darwin-arm64 • macOS 14.1.1 23B81 darwin-arm64 • Chrome (web) • chrome • web-javascript • Google Chrome 119.0.6045.159 ! Error: Browsing on the local area network for Pankaj’s iPhone. Ensure the device is unlocked and attached with a cable or associated with the same local area network as this Mac. The device must be opted into Developer Mode to connect wirelessly. (code -27) [✓] Network resources • All expected network resources are available. • No issues found! ```
TimHoogstrate commented 1 year ago

Dear @gujjar1988,

Thanks for filing this issue. Can you elaborate a bit on the subject? Can you add some clear steps to reproduce and add the contents of your manifest file?

Kind regards,

gujjar1988 commented 1 year ago

<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" tools:ignore="MissingVersion">

<uses-feature
    android:name="android.hardware.camera"
    android:required="false" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_LOCATION" />

<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION" />

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:label="App"
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher"
    android:enableOnBackInvokedCallback="true">

    <service
        android:name="com.pravera.flutter_foreground_task.service.ForegroundService"
        android:foregroundServiceType="location"
        android:stopWithTask="true" />

    <provider
        android:name="androidx.core.content.FileProvider"
        android:authorities="${applicationId}"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"/>
    </provider>

    <activity
        android:showWhenLocked="true"
        android:turnScreenOn="true"

        android:name=".MainActivity"
        android:exported="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:hardwareAccelerated="true"
        android:windowSoftInputMode="adjustResize">
        <!-- Specifies an Android theme to apply to this Activity as soon as
             the Android process has started. This theme is visible to the user
             while the Flutter UI initializes. After that, this theme continues
             to determine the Window background behind the Flutter UI. -->
        <meta-data
            android:name="firebase_messaging_auto_init_enabled"
            android:value="false" />
        <meta-data
            android:name="firebase_analytics_collection_enabled"
            android:value="false" />

        <meta-data
          android:name="io.flutter.embedding.android.NormalTheme"
          android:resource="@style/NormalTheme" />

        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
        <intent-filter>
            <action android:name="FLUTTER_NOTIFICATION_CLICK" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

        <intent-filter>
            <action
                android:name="com.android_package_installer.content.SESSION_API_PACKAGE_INSTALLED"
                android:exported="false"/>
        </intent-filter>

    </activity>

    <activity
        android:name="com.yalantis.ucrop.UCropActivity"
        android:screenOrientation="portrait"
        android:theme="@style/Theme.AppCompat.Light.NoActionBar"/>

    <!-- Don't delete the meta-data below.
         This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />
    <meta-data
        android:name="com.google.firebase.messaging.default_notification_channel_id"
        android:value="high_importance_channel"/>
    <meta-data
        android:name="firebase_messaging_auto_init_enabled"
        android:value="false" />
    <meta-data
        android:name="firebase_analytics_collection_enabled"
        android:value="false" />

</application>

TimHoogstrate commented 1 year ago

Can you reproduce this in the example app too?

Kind regards,

gujjar1988 commented 1 year ago
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.

  // await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  if (kDebugMode) print("Handling a background message: ${message.messageId}");
  if (Platform.isAndroid) {
    String type = message.data['type'];
    if (type.isNotEmpty) {
      final SharedPreferences prefs = await SharedPreferences.getInstance();
      List<String> savedList = prefs.getStringList(StorageEnum.backgroundRemoteMessage.name) ?? [];
      savedList.add(type);
      await prefs.setStringList(StorageEnum.backgroundRemoteMessage.name, savedList);
      if (kDebugMode) print("${message.messageId} saved in DB.");
    }

  } else {
    message.checkAction();
  }
}

void main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await ApplicationState.instance.initialize();
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
    await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
    FlutterError.onError = FirebaseCrashlytics.instance.recordFlutterFatalError;
    RemoteConfig.setDefaults();

    AppApiManager.instance.startNetworkListener();

    SecureStorage.instance.box = GetStorage("MyStorage");
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
      DeviceOrientation.portraitDown,
    ]).then((value) => runApp(const MyApp()));

}
menezes85 commented 11 months ago

I Have exacly the same issue

TimHoogstrate commented 11 months ago

@menezes85,

Can you share detailed steps to reproduce?

Kind regards,

menezes85 commented 11 months ago

Hello, @TimHoogstrate I believe that this problem is related to the life cycle of the application, probably there must be some call native to onDestroy for the flutter that is not managing to be delivered and is therefore being imprisoned in the execution pile. I have a similar problem in my app and removing this call from onDestroy was solved, basically when the application is killed, flutter engine becomes detatched and the methodChannel can no longer be accessed. Just start app, and make some calls to geolocator and close, the issue will happen on console

mvanbeusekom commented 10 months ago

Thank you for adding the additional information. We have labelled the issue as a bug and added it to our backlog.

arsd-ansari commented 1 month ago

@mvanbeusekom Any update on this?