HMS-Core / hms-flutter-plugin

This repo contains all of Flutter HMS plugins.
https://developer.huawei.com/consumer/en/doc/overview/HMS-Core-Plugin?ha_source=hms1
Apache License 2.0
294 stars 147 forks source link

Getting MissingPluginException when using with Huawei Location inside workmanager #360

Open chzhhong97 opened 7 months ago

chzhhong97 commented 7 months ago

Description When using huawei_location inside workmanager executeTask, it show Missing Plugin Exception

Expected behavior Able to get location

Current behavior Get Missing Plugin Exception

Logs

I/Hwaps   (13042): APS: EventAnalyzed: initAPS: version is 11.0.0.4
D/Hwaps   (13042): Fpsrequest create,type:EXACTLY_IDENTIFY
D/Hwaps   (13042): Fpsrequest create,type:EXACTLY_IDENTIFY
D/Hwaps   (13042): Fpsrequest create,type:OPENGL_SETTING
D/Hwaps   (13042): FpsController create
D/Hwaps   (13042): APS: EventAnalyzed: reInitFpsPara :mBaseFps = 120; mMaxFps = 120
W/Settings(13042): Setting device_provisioned has moved from android.provider.Settings.Secure to android.provider.Settings.Global.
V/HiTouch_HiTouchSensor(13042): User setup is finished.
W/HwApsManager(13042): HwApsManagerService, registerCallback, start !
D/Hwaps   (13042): APS: EventAnalyzed: registerCallbackInApsManagerService, mPkgName:com.rcs.linked.dev; result = true
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] current resolutionScale: 1.0
V/AudioManager(13042): querySoundEffectsEnabled...
I/AudioManager(13042): querySoundEffectsEnabled fail id: 0
W/FlutterJNI(13042): FlutterJNI.loadLibrary called more than once
D/FlutterGeolocator(13042): Geolocator foreground service connected
D/FlutterGeolocator(13042): Initializing Geolocator services
D/FlutterGeolocator(13042): Flutter engine connected. Connected engine count 2
W/FlutterJNI(13042): FlutterJNI.prefetchDefaultFontManager called more than once
I/ResourceExtractor(13042): Found extracted resources res_timestamp-1-1712682396453
W/FlutterJNI(13042): FlutterJNI.init called more than once
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] start to get views' rect, type = SCENE_GESTURE_SINGLE_TAP
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] windowModeType: 1
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] displayPoint: Point(1084, 2412)
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] windowModeType: 1
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] lazyMode:
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] current mode is full screen
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] start to getViewHierarchy
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] deviceOrientation: 0
D/HwViewRootImpl(13042): [DetectViewsLocationRunner-ScreenDirection] ROTATION_0
D/HwViewRootImpl(13042): [DetectViewsLocationRunner] get views' rect = 0, SCENE_GESTURE_SINGLE_TAP
I/flutter (13042): MissingPluginException(No implementation found for method initFusedLocationService on channel com.huawei.flutter.location/fusedlocation_methodchannel)
I/WM-WorkerWrapper(13042): Worker result RETRY for Work [ id=0bb6454c-33ce-4b86-8aab-e12faa2fa88d, tags={ dev.fluttercommunity.workmanager.BackgroundWorker } ]
D/FlutterGeolocator(13042): Flutter engine disconnected. Connected engine count 1
D/FlutterGeolocator(13042): Disposing Geolocator services
E/FlutterGeolocator(13042): Geolocator position updates stopped
E/FlutterGeolocator(13042): There is still another flutter engine connected, not stopping location service

Environment

Flutter Doctor [√] Flutter (Channel stable, 3.16.9, on Microsoft Windows [Version 10.0.22631.3296], locale en-US) [√] Windows Version (Installed version of Windows is version 10 or higher) [√] Android toolchain - develop for Android devices (Android SDK version 34.0.0) [√] Chrome - develop for the web [√] Visual Studio - develop Windows apps (Visual Studio Community 2022 17.8.1) [√] Android Studio (version 2021.3) [√] Android Studio (version 2023.2) [√] IntelliJ IDEA Community Edition (version 2023.2) [√] Connected device (4 available) [√] Network resources

• No issues found!

Sample Code

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  runApp(const App());
}

class App extends StatelessWidget{
  const App({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Test Services',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: HomePage(),
    );
  }
}

@pragma('vm:entry-point')
void workManagerCallbackDispatcher(){
  Workmanager().executeTask((taskName, inputData) async {
    try{
      //get location
      final fusedLocationClient = FusedLocationProviderClient();
      await fusedLocationClient.initFusedLocationService();

      var locationRequest = LocationRequest();
      var locationSettingsRequest = LocationSettingsRequest(
        requests: [locationRequest],
        needBle: true,
        alwaysShow: true,
      );

      try{
        var states = await fusedLocationClient.checkLocationSettings(locationSettingsRequest);
        print(states);
      }
      catch(e){
        rethrow;
      }

      await fusedLocationClient.requestLocationUpdates(locationRequest);
      final currentLocation = await fusedLocationClient.getLastLocation();

      print(currentLocation.toJson());
    }
    catch(e){
      print(e.toString());
      return false;
    }

    return true;
  });
}

class HomePage extends StatefulWidget{
  @override
  State<StatefulWidget> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
  }

  bool? showList = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Center(
          child: Column(
            children: [
              ElevatedButton(onPressed: () => initWorkmanager(), child: Text('Init Work Manager')),
              ElevatedButton(onPressed: () => Workmanager().cancelAll(), child: Text('Cancel All'))
            ],
          ),
        ),
      ),
    );
  }

  void initWorkmanager() async {
    await Workmanager().initialize(
      workManagerCallbackDispatcher,
    );

    await Workmanager().registerPeriodicTask('periodic-task', 'location-task');
  }
}

DartPluginRegistrant.ensureInitialized() is not include in this code because Workmanger already call this function before executeTask, and yes I also try call this function before executeTask but not working

tententenponce commented 6 months ago

I have the exact problem but I'm using it in foregroundService.

baggio2007 commented 6 days ago

Does anyone know how to solve the same problem? flutter version :3.24.1