When we travel, we usually need to book a hotel in the hotel App. Then, how to obtain the user’s geographical location information in the hotel APP so as to realize the functional search of “nearby hotels”? For this reason, I developed an app called Hotel Booking.

In this article, I’ll integrate the location service and show you how to use the getLastLocation and getLocationWithAddress methods, how to use the callback method, and how to store data into Shared Preferences in the Flutter application.

Location-based services

Location-based services help developers’ applications quickly and accurately retrieve a user’s location and extend their global positioning capabilities with GPS, Wi-Fi and base station positioning capabilities.

Fusion Location: Provides an easy-to-use API that allows you to quickly obtain user device location based on GPS, Wi-Fi, and base station location data.

Activity recognition: Identifies user activity through accelerometers, cellular network information, and magnetometers to help you adapt your application to user behavior.

Geo-fencing: You can set up an area of interest via the API so that your application can receive notifications when certain actions (such as leaving, entering, or staying in the area) occur.

Software requirements

  1. Android Studio 3.X
  2. JDK 1.8 and above
  3. SDK Platform 19 and above
  4. Gradle 4.6 and above

The integration steps

  1. Sign up for Huawei developer account in AppGallery Connect.
  2. Refer to the sections “Creating your AGC project” and “Adding an application under a project” to create an application.
  3. Set the data processing location according to the current location.
  4. Required service: Huawei location service.
  5. Generate the signature certificate fingerprint.
  6. Configure the signature certificate fingerprint.
  7. Copy your agconnect-services.json file to your application-level root directory.

Important: When adding an application, enter the same application package name as your Flutter project package name.

Note: Before downloading the agconnect-services.json file, make sure that the required HMS service is enabled.

The development process

Create an application in Android Studio.

  1. Create the Flutter project.
  2. Add a compile dependency.

A) App-level Gradle dependencies:

In the project, select "Android > app > build.gradle". apply plugin: 'com.android.application' apply plugin: 'com.huawei.agconnect'

B) Project Gradle dependencies:

Maven {url 'https://developer.huawei.com/repo/'} classpath 'com. Huawei. Agconnect: agcp: 1.4.1.300'

Add the following permissions to the AndroidManifest.xml file:

<uses-permission android:name="android.permission.INTERNET" />
 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
 <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
 <uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
 <uses-permission android:name="com.huawei.hms.permission.ACTIVITY_RECOGNITION" />
  1. See the link to download the required cross-platform plug-ins.
  2. After completing all the above steps, add a dependency to the Flutter plug-in for the required HMS service in the pubspec.yaml file. You can find the latest version of the plug-in at pub.dev.
^0.5.12+ 4Bottom_navy_bar: ^5.6.0 Cupertino_icons: ^1.0.0 Provider: ^4.3.3 HUAWEI_Location: Path:.. /huawei_location/ flutter: uses-material-design: true assets: - assets/images/
  1. After adding it, execute the Flutter Pub Get command. At this point, all the plug-ins are ready.
  2. Open the main.dart file to create the UI and business logic.

Integrated location service

permissions

First, the application needs to have access to both location data and physical data.

Create a PermissionHandler instance and call the initState() method to initialize the instance.

final PermissionHandler permissionHandler;
@override
 void initState() {
 permissionHandler = PermissionHandler(); super.initState();
 }

Check the permissions

Call the hasLocationPermission() method to check whether the device has the required permissions.

void hasPermission() async { try { final bool status = await permissionHandler.hasLocationPermission(); if(status == true){ showToast("Has permission: $status"); }else{ requestPermission(); } } on PlatformException catch (e) { showToast(e.toString()); }}

If the device without the required permissions, call requestLocationPermission () method to apply for relevant permissions.

void requestPermission() async { try { final bool status = await permissionHandler.requestLocationPermission(); showToast("Is permission granted"); } on PlatformException catch (e) { showToast(e.toString()); }}

Fusion positioning

Use the init () method creates FusedLocationPrvoiderClient instance, and then use this instance call API.

final FusedLocationProviderClient locationService
 
@override
 void initState() {
 locationService = FusedLocationProviderClient(); super.initState();
 }

Location update event

Call the onLocationData() method to listen for location update events.

StreamSubscription<Location> streamSubscription @override void initState() { streamSubscription = locationService.onLocationData.listen((location) {}); super.initState(); }

getLastLocation()

void getLastLocation() async { try { Location location = await locationService.getLastLocation(); setState(() { lastlocation = location.toString(); print("print: " + lastlocation); }); } catch (e) { setState(() { print("error: " + e.toString()); }); }}

getLastLocationWithAddress()

Create an instance of LocationRequest and set the parameters.

final LocationRequest locationRequest; locationRequest = LocationRequest() .. needAddress = true .. interval = 5000; void _getLastLocationWithAddress() async { try { HWLocation location = await locationService.getLastLocationWithAddress(locationRequest); setState(() { String street = location.street; String city = location.city; String countryname = location.countryName; currentAddress = '$street' + ',' + '$city' + ' , ' + '$countryname'; print("res: $location"); }); showToast(currentAddress); } on PlatformException catch (e) { showToast(e.toString()); }}

Location update via Callback

Create an instance of the LocationCallback and create the callback function in initState ().

LocationCallback locationCallback;
@override
 void initState() {
   locationCallback = LocationCallback(
     onLocationResult: _onCallbackResult,
     onLocationAvailability: _onCallbackResult,
   );
   super.initState();
 }
 
void requestLocationUpdatesCallback() async {
   if (_callbackId == null) {
     try {
       final int callbackId = await locationService.requestLocationUpdatesExCb(
           locationRequest, locationCallback);
       _callbackId = callbackId;
     } on PlatformException catch (e) {
       showToast(e.toString());
     }
   } else {
     showToast("Already requested location updates.");
   }
 }
 
 void onCallbackResult(result) {
   print(result.toString());
   showToast(result.toString());
 }

I created a Helper class for storing user login information locally through Shared Preferences.

class StorageUtil { static StorageUtil _storageUtil; static SharedPreferences _preferences; static Future<StorageUtil> getInstance() async { if (_storageUtil == null) { var secureStorage = StorageUtil._(); await secureStorage._init(); _storageUtil = secureStorage; } return _storageUtil; } StorageUtil._(); Future _init() async { _preferences = await SharedPreferences.getInstance(); } // get string static String getString(String key) { if (_preferences == null) return null; String result = _preferences.getString(key) ?? null; print('result,$result'); return result; } // put string static Future<void> putString(String key, String value) { if (_preferences == null) return null; print('result $value'); return _preferences.setString(key, value); }}

The results of

Warm prompt

  1. Please download the latest version of the Flutter plug-in for the HMS service.
  2. If you want to use the emulated location feature, you need to add the relevant permissions to the AndroidManifest.xml file.
  3. To update the plugin, click the PUG GET button.

For more details on HMS Core, please refer to: Huawei Developer Union official website to get development guidance documents and participate in developer discussions. Please download demos and sample code from CSDN or Reddit

The original link: https://developer.huawei.com/… Author: Pepper