Giter Site home page Giter Site logo

ysnksy / react-native-location-enabler Goto Github PK

View Code? Open in Web Editor NEW
157.0 2.0 25.0 3 MB

This package makes it easy for an React Native App to ensure that the Android device's system settings are properly configured for the app's location needs. If your app needs to request location, the device needs to enable the appropriate system settings, such as GPS or Wi-Fi scanning. Rather than directly enabling services such as the device's GPS, your app specifies the required level of accuracy/power consumption, and the device automatically makes the appropriate changes to system settings.

License: MIT License

Kotlin 24.37% JavaScript 6.54% Java 28.13% TypeScript 40.96%
react-native android location settings gps wifi bluetooth ble accuracy android-device

react-native-location-enabler's Introduction

react-native-location-enabler

GitHub version npm version Last Release Pull Request GitHub issues PRs Welcome

Platform - Android styled with Prettier semantic-release GitHub license

This package makes it easy for an React Native App to ensure that the Android device's system settings are properly configured for the app's location needs. If your app needs to request location, the device needs to enable the appropriate system settings, such as GPS or Wi-Fi scanning. Rather than directly enabling services such as the device's GPS, your app specifies the required level of accuracy/power consumption, and the device automatically makes the appropriate changes to system settings.


Installation

yarn add react-native-location-enabler

Usage

Example using Hook (React Hooks API) :

import LocationEnabler from 'react-native-location-enabler';

const {
  PRIORITIES: { HIGH_ACCURACY },
  useLocationSettings,
} = LocationEnabler;

// React Component
const App = () => {
  const [enabled, requestResolution] = useLocationSettings(
    {
      priority: HIGH_ACCURACY, // default BALANCED_POWER_ACCURACY
      alwaysShow: true, // default false
      needBle: true, // default false
    },
    false /* optional: default undefined */
  );

  return (
    <View>
      {!enabled && (
        <Button
          onPress={requestResolution}
          title="Request Resolution Location Settings"
        />
      )}
    </View>
  );
};

Example using Listener :

import LocationEnabler from "react-native-location-enabler"

const {
  PRIORITIES: { HIGH_ACCURACY },
  addListener,
  checkSettings,
  requestResolutionSettings
} = LocationEnabler

// Adds a listener to be invoked when location settings checked using
// [checkSettings] or changed using [requestResolutionSettings]
const listener = addListener(({ locationEnabled }) =>
  console.log(`Location are ${ locationEnabled ? 'enabled' : 'disabled' }`);
);

// Define configuration
const config = {
  priority: HIGH_ACCURACY, // default BALANCED_POWER_ACCURACY
  alwaysShow: true, // default false
  needBle: false, // default false
};

// Check if location is enabled or not
checkSettings(config);

// If location is disabled, prompt the user to turn on device location
requestResolutionSettings(config);

// ...
// Removes this subscription
listener.remove();

Example React Native App :

Clone the repo

git clone https://github.com/YsnKsy/react-native-location-enabler.git && cd react-native-location-enabler

Install npm dependencies

yarn

Start Metro ( javascript bundler )

yarn example start

Install and launch example app on the device

yarn example android


API

Properties

PRIORITIES

import LocationEnabler from 'react-native-location-enabler';

const {
  HIGH_ACCURACY,
  BALANCED_POWER_ACCURACY,
  LOW_POWER,
  NO_POWER,
} = LocationEnabler.PRIORITIES;

Static object contain a list quality of service for location updates. If your application wants high accuracy location it should set prioprity to 'HIGH_ACCURACY'. If you want negligible power impact, but to still receive location updates when available, then set priority to 'NO_POWER'.


Methods

useLocationSettings({ priority, alwaysShow, needBle }, initialStatus?)

import LocationEnabler from 'react-native-location-enabler';

const {
  useLocationSettings,
  PRIORITIES: { HIGH_ACCURACY },
} = LocationEnabler;

const [enabled, requestResolution] = useLocationSettings({
  priority: HIGH_ACCURACY, // optional: default BALANCED_POWER_ACCURACY
  alwaysShow: true, // optional: default false
  needBle: true, // optional: default false
});

console.log(`Location are ${enabled ? 'enabled' : 'disabled'}`);

// ...
if (!enabled) {
  requestResolution();
}

Hook let you check the user's device location status 'on' / 'off' and method let you display an activity where they can turn location 'on'.


checkSettings({ priority, alwaysShow, needBle })

import LocationEnabler from 'react-native-location-enabler';

const {
  checkSettings,
  PRIORITIES: { HIGH_ACCURACY },
} = LocationEnabler;

checkSettings({
  priority: HIGH_ACCURACY, // optional: default BALANCED_POWER_ACCURACY
  alwaysShow: true, // optional: default false
  needBle: true, // optional: default false
});

Checking if the user's device location is turned on / off.


requestResolutionSettings({ priority, alwaysShow, needBle })

import LocationEnabler from 'react-native-location-enabler';

const {
  requestResolutionSettings,
  PRIORITIES: { HIGH_ACCURACY },
} = LocationEnabler;

requestResolutionSettings({
  priority: HIGH_ACCURACY, // optional: default BALANCED_POWER_ACCURACY
  alwaysShow: true, // optional: default false
  needBle: true, // optional: default false
});

Display an activity where they can turn location 'on' using a location request.


addListener(callback, context?)

import LocationEnabler from 'react-native-location-enabler';

let listener = null;

function cb(result) {
  const { locationEnabled } = result;

  console.log(`Location are ${locationEnabled ? 'enabled' : 'disabled'}`);

  if (listener !== null) {
    // remove listener when you finish
    listener.remove();
  }
}

listener = LocationEnabler.addListener(cb);

Adds a listener to be invoked when onChangeLocationSettings are emitted. An optional calling context may be provided. The data arguments emitted will be passed to the listener function.


Contributing

Press the STAR button ๐Ÿ˜€ and see the contributing guide to learn how to contribute to the repository and the development workflow.

Code of Conduct

See the code of conduct guide.

License

See the MIT License

react-native-location-enabler's People

Contributors

dependabot[bot] avatar imgbotapp avatar semantic-release-bot avatar ysnksy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-native-location-enabler's Issues

FEATURE ADD REQUEST: requestResolution / requestResolutionSettings should return the option selected by user, and more.

ISSUE 1:
As of now the requestResolution() method from the Hook or requestResolutionSettings() method does not return what option the user selected. It would be really helpful if those methods were promises and returned the option selected by the user. Because currently if the user selects no thanks, there is no way for us prompt again automatically.
Or if there is any other solution to my problem in the current state please suggest.

ISSUE 2:
The current checkSetting() method doesn't return true or false it returns void, there is no methods to check if LOCATION setting is turned on or not. I suggest checkSetting() method to return a boolean or add a separate method to check GPS (LOCATION) setting status of device. Or if there is a way without using listener to get the status of the mentioned setting, please let me know.
PS.: I should clarify I am not talking about location permissions, but the state of location / GPS turn on/off feature in android.

FAILURE: Build failed with an exception.

  • What went wrong:
    A problem occurred configuring project ':react-native-location-enabler'.
    Failed to notify project evaluation listener.
  • Could not create task ':react-native-location-enabler:compileDebugAndroidTestKotlin'.
  • Cannot use @TaskAction annotation on method AbstractKotlinCompile.execute() because interface org.gradle.api.tasks.incremental.IncrementalTaskInputs is not a valid parameter to an action method.
  • KotlinJvmAndroidCompilation with name 'debugAndroidTest' not found.

Issue in IOS

Invariant Violation: Native module cannot be null.[Mon Jul 05 2021 21:07:01.759] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)[Mon Jul 05 2021 21:07:02.849] ERROR Invariant Violation: Module AppRegistry is not a registered callable module (calling runApplication)

Getting this error while running on IOS

Example error: unable to resolve interopRequireDefault

Hi folks,
thank you so much for maintaining this repository. The documentation sounds promising. That is why I wanted to see it with my own eyes and tried it straight by myself. However, I could not run the example without errors. I ran these instructions.

yarn example
yarn example start
yarn example android

The result is the following error message from metro bundler:

[Fri Mar 26 2021 08:56:54.963]  BUNDLE  ./index.tsx 

error: Error: Unable to resolve module `@babel/runtime/helpers/interopRequireDefault` from `../src/index.ts`: @babel/runtime/helpers/interopRequireDefault could not be found within the project.

If you are sure the module exists, try these steps:
 1. Clear watchman watches: watchman watch-del-all
 2. Delete node_modules: rm -rf node_modules and run yarn install
 3. Reset Metro's cache: yarn start --reset-cache
 4. Remove the cache: rm -rf /tmp/metro-*
    at ModuleResolver.resolveDependency (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/node-haste/DependencyGraph/ModuleResolution.js:186:15)
    at ResolutionRequest.resolveDependency (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/node-haste/DependencyGraph/ResolutionRequest.js:52:18)
    at DependencyGraph.resolveDependency (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/node-haste/DependencyGraph.js:287:16)
    at Object.resolve (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/lib/transformHelpers.js:267:42)
    at /home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/DeltaBundler/traverseDependencies.js:434:31
    at Array.map (<anonymous>)
    at resolveDependencies (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/DeltaBundler/traverseDependencies.js:431:18)
    at /home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/DeltaBundler/traverseDependencies.js:275:33
    at Generator.next (<anonymous>)
    at asyncGeneratorStep (/home/stefan/git/react-native-location-enabler/example/node_modules/metro/src/DeltaBundler/traverseDependencies.js:87:24)

I also ran the four recommended steps from the error message without any change. First I thought this error might be due to metro bundler is not reading TypeScript. That is why I added this snippet to the metro configuration.

/*by default metro bundler does not compile files with extension .ts or .tsx*/
sourceExts:['jsx','js','ts','tsx'],

This configuration change also did not yield the desired effect. I am working with an Ubuntu 18.04 operating system with the following dev tool versions.

yarn --version 1.22.5
node --version v14.16.0

I checked out this repository as it is now at the time I am writing this issue. Does anyone can point me in the right direction? Cheers!

locationEnabled always return false in listener

let _gpsState = LocationEnabler.addListener(({ locationEnabled }) => {
console.log('location is enabled: ', locationEnabled);
setGpsState(locationEnabled);
});

^ When I called checkSettings() function, this will be triggered, however for some of the android phone, it is working properly, but for some other android phone like realme C35, it always return false

HI app crash due to onActivityResult receiving null intent

Hi the app was getting following error :-
Fatal Exception: java.lang.RuntimeException
Failure delivering result ResultInfo{who=null, request=1024, result=0, data=null} to activity {com.creditcard.onecard/com.creditcard.onecard.MainActivity}: java.lang.IllegalArgumentException: Parameter specified as non-null is null: method k.b0.d.k.d, parameter intent, as intent had no null handling,

I have added it in this fork: -https://github.com/ANIBIT14/react-native-location-enabler/tree/master/android/src/main/java/com/reactnativelocationenabler, you can check and update the code, in this package @YsnKsy

Issue on IOS

Hi, not able to run app in iOS after installing this library , issue is
Invariant Violation: new NativeEventEmitter() requires a non-null argument.
This issue is already reported and closed but its not fixed.

How should permission not being granted be handled?

So it is quite clear in the documentation how to check if location is not enabled and ask for permission to enable it.

But suppose, after asking for permission to enable location, the user does not grant it. And I want to show a message/alert saying because location permission was not granted, we cannot proceed further.

How can I handle this situation?

FAILURE: Build failed with an exception

kotlin_version = '1.9.0'
classpath('com.android.tools.build:gradle:7.4.2')

  • What went wrong:

The Android Gradle plugin supports only Kotlin Gradle plugin version 1.5.20 and higher.
The following dependencies do not satisfy the required version:
project ':react-native-location-enabler' -> org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50

Gets old setting sometimes

Not sure if this is 100% reproducible, but if first location is disabled, then it is asked and allowed to be enabled, and after that it is disabled again, the module detects as if it is still enabled.

Build Failed

Run android failed to build with the following error:

Execution failed for task ':react-native-location-enabler:compileDebugKotlin'.

last time i tried to build my project was Thursday and everything was normal.

ActivityEventListener listens to all requestCode

Hello,

I've got an issue when listening to LocationEnabler. locationEnabled is emitted as false each time I return from library selection activity for example.

This line prevents the listener to return early resulting in an incorrect interpretation of arguments.

For example if I've opened the library with a random request code 12345. Here the Intent is null. So the code continues.

if (intent !== null && requestCode != REQUEST_TURN_DEVICE_LOCATION_ON) return

I'd just remove the "intent !== null" part. Because I don't see any reason to continue if the request code is not 29. But maybe I'm missing an important detail here for why this is done with "intent !== null" ?

TypeError: Cannot read property 'HIGH_ACCURACY' of undefined

Got the fix actually but using the code which the library suggest is wrong, Posting it here just in case anyone is stuck because of it.

the code suggested by library :
const {HIGH_ACCURACY} = LocationEnabler.PRIORITIES;

Modified code :
const {HIGH_ACCURACY} = LocationEnabler.default.PRIORITIES;

Unable to run ESLint

After i included this package in my project, i am able to use it, but running eslint on my project, fails.

I get the following error:
Cannot find module '...\node_modules\react-native-location-enabler\lib\commonjs\index'. Please verify that the package.json has a valid "main" entry

The lib folder does not get created when restoring the package and causes eslint to fail.

The entry point 'main' in package.json needs to be changed to "main": "src/index.ts",

Not working with warning

new NativeEventEmitter() was called with a non-null argument without the required removeListeners method

This warning is showed, and not working

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.