GithubHelp home page GithubHelp logo

webyonet / react-native-android-location-services-dialog-box Goto Github PK

View Code? Open in Web Editor NEW
181.0 11.0 49.0 398 KB

React Native Android Location Services Dialog Box

License: MIT License

Java 99.04% JavaScript 0.96%
android dialog-box react-native location-services location geolocation geo locations dialog react

react-native-android-location-services-dialog-box's Introduction

React Native Android Location Services Dialog Box

A react-native component for turn on the dialog box from android location services

GitHub tag npm version npm npm npm

Installation

Mostly automatic installation (recommended)

  1. yarn add react-native-android-location-services-dialog-box
    or
    npm install react-native-android-location-services-dialog-box --save
  2. react-native link react-native-android-location-services-dialog-box

Manual Installation

Android
  1. yarn add react-native-android-location-services-dialog-box
    or
    npm install react-native-android-location-services-dialog-box --save
  2. Make the following additions to the given files:

android/settings.gradle

include ':react-native-android-location-services-dialog-box'
project(':react-native-android-location-services-dialog-box').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-android-location-services-dialog-box/android')

android/app/build.gradle

dependencies {
   ...
   compileOnly project(':react-native-android-location-services-dialog-box')
}

MainApplication.java

On top, where imports are:

import com.showlocationservicesdialogbox.LocationServicesDialogBoxPackage;

Under protected List<ReactPackage> getPackages() {:

  return Arrays.<ReactPackage>asList(
    new MainReactPackage(),
    new LocationServicesDialogBoxPackage() // <== this
  );

Usage

import { BackHandler, DeviceEventEmitter } from 'react-native';
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

LocationServicesDialogBox.checkLocationServicesIsEnabled({
    message: "<h2 style='color: #0af13e'>Use Location ?</h2>This app wants to change your device settings:<br/><br/>Use GPS, Wi-Fi, and cell network for location<br/><br/><a href='#'>Learn more</a>",
    ok: "YES",
    cancel: "NO",
    enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => GPS OR NETWORK PROVIDER
    showDialog: true, // false => Opens the Location access page directly
    openLocationServices: true, // false => Directly catch method is called if location services are turned off
    preventOutSideTouch: false, // true => To prevent the location services window from closing when it is clicked outside
    preventBackClick: false, // true => To prevent the location services popup from closing when it is clicked back button
    providerListener: false // true ==> Trigger locationProviderStatusChange listener when the location state changes
}).then(function(success) {
    console.log(success); // success => {alreadyEnabled: false, enabled: true, status: "enabled"}
}).catch((error) => {
    console.log(error.message); // error.message => "disabled"
});

BackHandler.addEventListener('hardwareBackPress', () => { //(optional) you can use it if you need it
   //do not use this method if you are using navigation."preventBackClick: false" is already doing the same thing.
   LocationServicesDialogBox.forceCloseDialog();
});

DeviceEventEmitter.addListener('locationProviderStatusChange', function(status) { // only trigger when "providerListener" is enabled
    console.log(status); //  status => {enabled: false, status: "disabled"} or {enabled: true, status: "enabled"}
});

componentWillUnmount() {
    // used only when "providerListener" is enabled
    LocationServicesDialogBox.stopListener(); // Stop the "locationProviderStatusChange" listener
}

Configure Colors

import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

LocationServicesDialogBox.checkLocationServicesIsEnabled({
    message: "<font color='#f1eb0a'>Use Location ?</font>",
    ok: "YES",
    cancel: "NO",
    style: { // (optional)
        backgroundColor: '#87a9ea',// (optional)
        
        positiveButtonTextColor: '#ffffff',// (optional)
        positiveButtonBackgroundColor: '#5fba7d',// (optional)
        
        negativeButtonTextColor: '#ffffff',// (optional)
        negativeButtonBackgroundColor: '#ba5f5f'// (optional)
    }
}).then(function(success) {
    console.log(success);
}).catch((error) => {
    console.log(error.message);
});

screen shot 2018-07-07 at 16 58 28

Usage And Example For Async Method ES6

import { BackHandler, DeviceEventEmitter } from 'react-native';
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

export default class LocationServiceTestPage extends Component {
    constructor(props){
        super(props);
        
        this.checkIsLocation().catch(error => error);
        
        DeviceEventEmitter.addListener('locationProviderStatusChange', function(status) { // only trigger when "providerListener" is enabled
            console.log(status); //  status => {enabled: false, status: "disabled"} or {enabled: true, status: "enabled"}
        });
    }
    
    async checkIsLocation():Promise {
        let check = await LocationServicesDialogBox.checkLocationServicesIsEnabled({
            message: "Use Location ?",
            ok: "YES",
            cancel: "NO",
            enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => GPS OR NETWORK PROVIDER
            showDialog: true, // false => Opens the Location access page directly
            openLocationServices: true, // false => Directly catch method is called if location services are turned off
            preventOutSideTouch: false, //true => To prevent the location services window from closing when it is clicked outside
            preventBackClick: false, //true => To prevent the location services popup from closing when it is clicked back button
            providerListener: true // true ==> Trigger "locationProviderStatusChange" listener when the location state changes
        }).catch(error => error);

        return Object.is(check.status, "enabled");
    }
    
    componentWillUnmount() {
        // used only when "providerListener" is enabled
        LocationServicesDialogBox.stopListener(); // Stop the "locationProviderStatusChange" listener
    }   
}

Examples ES6

import React, { Component } from 'react';
import {
    AppRegistry,
    Text,
    View,
    BackHandler,
    DeviceEventEmitter
} from 'react-native';

import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";

class SampleApp extends Component {
    state = {
        initialPosition: 'unknown',
    };

    componentDidMount() {
        LocationServicesDialogBox.checkLocationServicesIsEnabled({
            message: "<h2>Use Location ?</h2>This app wants to change your device settings:<br/><br/>Use GPS, Wi-Fi, and cell network for location<br/><br/><a href='#'>Learn more</a>",
            ok: "YES",
            cancel: "NO",
            enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => GPS OR NETWORK PROVIDER
            showDialog: true, // false => Opens the Location access page directly
            openLocationServices: true, // false => Directly catch method is called if location services are turned off
            preventOutSideTouch: false, //true => To prevent the location services popup from closing when it is clicked outside
            preventBackClick: false, //true => To prevent the location services popup from closing when it is clicked back button
            providerListener: true // true ==> Trigger "locationProviderStatusChange" listener when the location state changes
        }).then(function(success) {
            // success => {alreadyEnabled: true, enabled: true, status: "enabled"} 
                navigator.geolocation.getCurrentPosition((position) => {
                    let initialPosition = JSON.stringify(position);
                    this.setState({ initialPosition });
                }, error => console.log(error), { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 });
            }.bind(this)
        ).catch((error) => {
            console.log(error.message);
        });
        
        DeviceEventEmitter.addListener('locationProviderStatusChange', function(status) { // only trigger when "providerListener" is enabled
            console.log(status); //  status => {enabled: false, status: "disabled"} or {enabled: true, status: "enabled"}
        });
    }
    
    componentWillUnmount() {
        // used only when "providerListener" is enabled
        LocationServicesDialogBox.stopListener(); // Stop the "locationProviderStatusChange" listener.
    } 

    render() {
        return (
            <View>
                <Text>
                    Geolocation: {this.state.initialPosition}
                </Text>
            </View>
        );
    }
}
AppRegistry.registerComponent('SampleApp', () => SampleApp);

Props

Prop Type Default Description
message HTML null Dialog box content text
ok String null Dialog box ok button text
cancel String null Dialog box cancel button text
enableHighAccuracy (optional) Boolean true Provider switch (GPS OR NETWORK OR GPS AND NETWORK)
showDialog (optional) Boolean true Indicate whether to display the dialog box
openLocationServices (optional) Boolean true Indicate whether to display the location services screen
preventOutSideTouch (optional) Boolean true To prevent the location services window from closing when it is clicked outside
preventBackClick (optional) Boolean true To prevent the location services popup from closing when it is clicked back button
providerListener (optional) Boolean false Used to trigger `locationProviderStatusChange listener when the location state changes.
style (optional) Object {} Change colors

Methods

Name Return Return Value
checkLocationServicesIsEnabled Promise Object
forceCloseDialog (optional using) void -
stopListener (optional using) void -

react-native-android-location-services-dialog-box's People

Contributors

cody-g-g avatar dabit1 avatar frmrgr avatar gasperz avatar minishlink avatar radko93 avatar reyalpsirc avatar sanderverkuil avatar sathiyamm avatar tobirohrer avatar waqas19921 avatar webyonet 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-android-location-services-dialog-box's Issues

function LocationServiceDialogBox.checkLocationServicesIsEnabled error

this error occur when I run my app on android devices, please help me. Thanks

This is my code

import React, { Component } from "react";
import {
	Text,
	StyleSheet,
	View,
	TouchableOpacity, Platform
} from "react-native";
import LocationServiceDialogBox from "react-native-android-location-services-dialog-box";
// import { platform } from "os";
export default class WelcomeScreen extends Component {
	constructor(props) {
		super(props);

		this.state = {
			latitude: null,
			longitude: null,
			error: null,
			initialPosition: "unknown"
		};
	}
	componentDidMount() {
		navigator.geolocation.getCurrentPosition(
			position => {
				this.setState({
					latitude: position.coords.latitude,
					longitude: position.coords.longitude,
					error: null
				});
			},
			error => this.setState({ error: error.message }),
			{ enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 }
		);
		if (Platform.OS === "android")
			LocationServiceDialogBox.checkLocationServicesIsEnabled({
				message:
					"<h2> Use Location?</h2>This app wants to change your device settings:<br/><br/>Use GPS, Wi-fi, and cell network for location<br/><br/><a href='#'>Learn more</a>",
				ok: "YES",
				cancel: "NO",
				enableHighAccuracy: true,
				showDialog: true,
				openLocationServices: true,
				preventOutSideTouch: false,
				preventBackClick: false
			})
				.then(
					function(success) {
						navigator.geolocation.getCurrentPosition(
							position => {
								let initialPosition = JSON.stringify(position);
								this.setState({ initialPosition });
							},
							error => console.log(error),
							{
								enableHighAccuracy: false,
								timeout: 20000,
								maximumAge: 1000
							}
						);
					}.bind(this)
				)
				.catch(error => {
					console.log(error.message);
				});
		BackHandler.addEventListener("hardwareBackPress", () => {
			LocationServiceDialogBox.forceCloseDialog();
		});
	}
	// onPress = () => {
	// 	this.props.navigation.navigate("Login");
	// };
	render() {
		return (
			<View style={styles.container}>
				<Text>WelcomeScreen</Text>
				<Text>Latitude: {this.state.latitude}</Text>
				<Text>Longitude: {this.state.longitude}</Text>
				{this.state.error ? (
					<Text>Error: {this.state.error}</Text>
				) : null}
				<Text>Geolocation: {this.state.initialPosition}</Text>
				<TouchableOpacity
					style={styles.btnLetsGo}
					onPress={() => this.props.navigation.navigate("Login")}
				>
					<Text style={styles.txtBtn}>Let's GO!</Text>
				</TouchableOpacity>
			</View>
		);
	}
}

const styles = StyleSheet.create({
	container: {
		flex: 1,
		alignItems: "center",
		justifyContent: "center",
		backgroundColor: "cyan"
	},
	btnLetsGo: {
		justifyContent: "center",
		alignItems: "center",
		backgroundColor: "#ffcc00"
	}
});

TypeError: undefined is not an object (evaluating '_reactNativeAndroidLocationServicesDialogBox2.default.checkLocationServicesIsEnabled')

This error is located at:
    in WelcomeScreen (at SceneView.js:17)
    in SceneView (at CardStack.js:455)
    in RCTView (at View.js:60)
    in View (at CardStack.js:454)
    in RCTView (at View.js:60)
    in View (at CardStack.js:453)
    in RCTView (at View.js:60)
    in View (at createAnimatedComponent.js:154)
    in AnimatedComponent (at Card.js:12)
    in Card (at PointerEventsContainer.js:39)
    in Container (at CardStack.js:498)
    in RCTView (at View.js:60)
    in View (at CardStack.js:414)
    in RCTView (at View.js:60)
    in View (at CardStack.js:413)
    in CardStack (at CardStackTransitioner.js:67)
    in RCTView (at View.js:60)
    in View (at Transitioner.js:142)
    in Transitioner (at CardStackTransitioner.js:19)
    in CardStackTransitioner (at StackNavigator.js:41)
    in Unknown (at createNavigator.js:13)
    in Navigator (at createNavigationContainer.js:226)
    in NavigationContainer (at App.js:8)
    in App (at registerRootComponent.js:35)
    in RootErrorBoundary (at registerRootComponent.js:34)
    in ExpoRootComponent (at renderApplication.js:33)
    in RCTView (at View.js:60)
    in View (at AppContainer.js:102)
    in RCTView (at View.js:60)
    in View (at AppContainer.js:122)
    in AppContainer (at renderApplication.js:32)

The props are useless

I try to use preventOutSideTouch and preventBackClick, but I can still close dialog by clicking outside and pressing back button.
I checked your code. No preventOutSideTouch and preventBackClick in there.

Error in building

Hey,
When I am doing react-native run-android, it gives me 3 errors;

  1. LocationServicesDialogBoxModule is not abstract and does not override abstract method onActivityResult(int,int, Intent).
  2. LocationServicesDialogBoxModule.java:25: error: method does not override or implement a method from a supertype
    The third one is same as second one but with different file no
  3. LocationServicesDialogBoxModule.java:125: error: method does not override or implement a method from a supertype

It also gives a note saying that the module LocationServicesDialogBoxModule uses or overrides a deprecated API.

Tried uninstalling/installing this module but of no use.
Tried a clean build but also did not helped.

React-native version is 0.27.2 and cli's 2.0.1

Build failed with an exception.

react-native-android-lo cation-services-dialog-box/android/src/main/java/com/showlocationservicesdial ogbox/LocationServicesDialogBoxModule.java:13: error: LocationServicesDialogBoxModule is not abstract and does not override abstract method onActivityResult(int,int,Intent) in ActivityEventListener class LocationServicesDialogBoxModule extends ReactContextBaseJavaModule implements ActivityEventListener { ^ /home/algofocus/ReactNativeProjects/PSP2/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocationservicesdialogbox/LocationServicesDialogBoxModule.java:25: error: method does not override or implement a method from a supertype @Override ^ /home/algofocus/ReactNativeProjects/PSP2/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocationservicesdialogbox/LocationServicesDialogBoxModule.java:125: error: method does not override or implement a method from a supertype @Override ^ Note: /home/algofocus/ReactNativeProjects/PSP2/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocationservicesdialogbox/LocationServicesDialogBoxModule.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. 3 errors
when using with firebase crashlytics

"react": "16.3.1",
"react-native": "0.55.4",
"react-native-android-location-services-dialog-box": "^2.4.4",

Location service not working after building the project

Getting this error

undefined is not an object (evaluating '_reactnative android locationservice dialogbox 2.default.check locationservice isenabled')

Thinking is this only for ejected apps or can this location checking use on every app?

No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

creating a release build having issues. Debug build works fine though

.gradle/caches/transforms-1/files-1.1/appcompat-v7-26.1.0.aar/4a9597cd76950081cc172f93c5d7c4da/res/values-v26/values-v26.xml:13:5-16:13: AAPT: No resource found that matches the given name: attr 'android:keyboardNavigationCluster'.

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':react-native-android-location-services-dialog-box:verifyReleaseResources'.

com.android.ide.common.process.ProcessException: Failed to execute aapt

crashed when click ok

The plugin seems to work fine on Simulator but on device it crashed the app when I click OK. It was on development mode. I manage to get this error messages.

FATAL EXCEPTION: mqt_native_modules
Process: com.smish, PID: 2775
android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.LOCATION_SOURCE_SETTINGS VirtualScreenParam=Params{mDisplayId=-1, null, mFlags=0x00000000)} }
	at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1878)
	at android.app.Instrumentation.execStartActivity(Instrumentation.java:1545)
	at android.app.Activity.startActivityForResult(Activity.java:4283)
	at android.app.Activity.startActivityForResult(Activity.java:4230)
	at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule$2.onClick(LocationServicesDialogBoxModule.java:63)
	at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:173)
	at android.os.Handler.dispatchMessage(Handler.java:102)
	at android.os.Looper.loop(Looper.java:158)
	at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
	at java.lang.Thread.run(Thread.java:818)


android.view.WindowLeaked: Activity com.smish.MainActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{5171d50 V.E...... R......D 0,0-1010,503} that was originally added here
	at android.view.ViewRootImpl.<init>(ViewRootImpl.java:565)
	at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:326)
	at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
	at android.app.Dialog.show(Dialog.java:350)
	at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.displayPromptForEnablingGPS(LocationServicesDialogBoxModule.java:74)
	at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.checkLocationService(LocationServicesDialogBoxModule.java:48)
	at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.checkLocationServicesIsEnabled(LocationServicesDialogBoxModule.java:36)
	at java.lang.reflect.Method.invoke(Native Method)
	at com.facebook.react.bridge.BaseJavaModule$JavaMethod.invoke(BaseJavaModule.java:318)
	at com.facebook.react.cxxbridge.JavaModuleWrapper.invoke(JavaModuleWrapper.java:158)
	at com.facebook.react.bridge.queue.NativeRunnable.run(Native Method)
	at android.os.Handler.handleCallback(Handler.java:739)
	at android.os.Handler.dispatchMessage(Handler.java:95)
	at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:31)
	at android.os.Looper.loop(Looper.java:158)
	at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:196)
	at java.lang.Thread.run(Thread.java:818)

Build error

  • What went wrong:
    Execution failed for task ':react-native-android-location-services-dialog-box:compileReleaseJavaWithJavac'.

Could not find tools.jar. Please check that C:\Program Files\Java\jre0_144 contains a valid JDK installation.

locationProviderStatusChange listener callback method calling multiple times when closing (on/off) location from notification tray.

constructor(){
super();
this.DeviceEventEmitterListener = this.DeviceEventEmitterListener.bind(this);
}

componentWillMount(){

  DeviceEventEmitter.addListener('locationProviderStatusChange',this.DeviceEventEmitterListener);

this.enableLocations();
}

componentWillUnmount() {

  LocationServicesDialogBox.stopListener();

}

DeviceEventEmitterListener=(params) => {

  alert(params);  // ISSUE:  alert showing multiple times when the user closes app multiple times.

}

enableLocations(){

LocationServicesDialogBox.checkLocationServicesIsEnabled({
  message: "<h2>Use Location ?</h2>This app wants to change your device settings:<br/><br/>Use 
 GPS, Wi-Fi, and cell network for location<br/><br/>",
  ok: "YES",
  cancel: "NO",
  enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => GPS OR NETWORK PROVIDER
  showDialog: true, // false => Opens the Location access page directly
  openLocationServices: true, // false => Directly catch method is called if location services are turned off
  preventOutSideTouch: false, // true => To prevent the location services window from closing when it is clicked outside
  preventBackClick: true, // true => To prevent the location services popup from closing when it is clicked back button
  providerListener: true // true ==> Trigger locationProviderStatusChange listener when the location state changes

}).then((success) =>{
console.log(success); // success => {alreadyEnabled: false, enabled: true, status: "enabled"}

  if(success.enabled){
    this.setState({
      locationEnabled: true
          });
          this.getPermission();  // get android app level permissions
  }else{

    this.setState({
      locationEnabled: false
          }); 
  }  

}).catch((error) => {

  // if user open settings screen and comes back without enabling location  reopen dialog or user 
 //  clicks no in location enable dialog
  this.enableLocations();

});
}

Error when building project with react-native-android-location-services-dialog-box

When I try to run a project with this module I get these errors:

`/home/user/appAndroid/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocation
servicesdialogbox/LocationServicesDialogBoxModule.java:12: error: LocationServicesDialogBoxModule is not abstract and does not ove
rride abstract method onActivityResult(int,int,Intent) in ActivityEventListener
class LocationServicesDialogBoxModule extends ReactContextBaseJavaModule implements ActivityEventListener {
^
/home/user/appAndroid/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocation
servicesdialogbox/LocationServicesDialogBoxModule.java:22: error: method does not override or implement a method from a supertype
@OverRide
^
/home/user/appAndroid/node_modules/react-native-android-location-services-dialog-box/android/src/main/java/com/showlocation
servicesdialogbox/LocationServicesDialogBoxModule.java:77: error: method does not override or implement a method from a supertype
@OverRide
^
3 errors
:react-native-android-location-services-dialog-box:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.`

I have react-native version 31.0

Location request timed out

Hi,
The dialog works fine, location service is correctly opened and my callback is correctly invoked.

The problem is if I call the native method :
navigator.geolocation.getCurrentPosition(resolve, reject)

If the location was enabled by the dialog box I have always the same response
error {TIMEOUT: 3, POSITION_UNAVAILABLE: 2, PERMISSION_DENIED: 1, message: "Location request timed out", code: 3}

RN : .57.2
react-native-android-location-services-dialog-box: 2.7

Location is already enabled but location service dialog box is showing

I use this code

import { BackHandler } from 'react-native';
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";
export function requestLocationPermission() {
    try {
LocationServicesDialogBox.checkLocationServicesIsEnabled({
    message: "<h2>Use Location ?</h2>This app wants to change your device settings:<br/><br/>Use GPS, Wi-Fi, and cell network for location<br/><br/><a href='#'>Learn more</a>",
    ok: "YES",
    cancel: "NO",
    enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => ONLY GPS PROVIDER
    showDialog: true, // false => Opens the Location access page directly
    openLocationServices: true, // false => Directly catch method is called if location services are turned off
    preventOutSideTouch: false, //true => To prevent the location services window from closing when it is clicked outside
    preventBackClick: false //true => To prevent the location services popup from closing when it is clicked back button
}).then(function(success) {
    console.log(success); // success => {alreadyEnabled: false, enabled: true, status: "enabled"}
}).catch((error) => {
    console.log(error.message); // error.message => "disabled"
});

BackHandler.addEventListener('hardwareBackPress', () => { //(optional) you can use it if you need it
   LocationServicesDialogBox.forceCloseDialog();
});
} catch (err) {
        console.warn(err)
    }
}

"gps" location provider requires ACCESS_FINE_LOCATION permission.

Hi, first of all, thank you for your work.
After an update I recently got the error :
Looks like the app doesn't have the permission to access location.

Add the following line to your app's AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

"gps" location provider requires ACCESS_FINE_LOCATION permission.
throwLocationPermissionMissing
    LocationModule.java:234
startObserving
    LocationModule.java:173
invoke
    Method.java
invoke
    JavaMethodWrapper.java:372
invoke
    JavaModuleWrapper.java:160
run
    NativeRunnable.java
handleCallback
    Handler.java:873
dispatchMessage
    Handler.java:99
dispatchMessage
    MessageQueueThreadHandler.java:29
loop
    Looper.java:193
run
    MessageQueueThreadImpl.java:192
run
    Thread.java:764

But I have in my AndroidManifest the line <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />.
Is this a bug or am I doing something wrong?

iOS support

Hi,

Thx for your package.
Can you make iOS supported with it ?

Rgds

Not working for me

When i am importing this package getting following error:

error: bundling failed: Error: While trying to resolve module `react-native-android-location-services-dialog-box` from file `/Users/vinove/SimSim_backup/simsimProject/app/components/maps/Maps.js`, the package `/Users/vinove/SimSim_backup/simsimProject/node_modules/react-native-android-location-services-dialog-box/package.json` was successfully found. However, this package itself specifies a `main` module field that could not be resolved (`/Users/vinove/SimSim_backup/simsimProject/node_modules/react-native-android-location-services-dialog-box/index.js`. Indeed, none of these files exist:

TypeError: Cannot read property 'checkLocationServicesIsEnabled' of undefined

package.json:
"react-native": "^0.51.0",
"react-native-android-location-services-dialog-box": "^2.4.3",

Code:

LocationServicesDialogBox.checkLocationServicesIsEnabled({
          message:
            "<h2>Use Location ?</h2>This app wants to change your device settings:<br/><br/>Use GPS, Wi-Fi, and cell network for location<br/><br/><a href='#'>Learn more</a>",
          ok: 'YES',
          cancel: 'NO',
          enableHighAccuracy: true, // true => GPS AND NETWORK PROVIDER, false => ONLY GPS PROVIDER
          showDialog: true, // false => Opens the Location access page directly
          openLocationServices: true,
          // false => Directly catch method is called if location services are turned off
          preventOutSideTouch: false,
          // true => To prevent the location services popup from closing when it is clicked outside
          preventBackClick: false,
          // true=>To prevent the location services popup from closing when it is clicked back
        })
          .then(success => {
            // success => {alreadyEnabled: true, enabled: true, status: "enabled"}
            navigator.geolocation.getCurrentPosition(
              position => {
                const initialPosition = JSON.stringify(position)
                this.setState({ initialPosition })
              },
              error => console.log(error),
              { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000 },
            )
          })
          .catch(error => {
            console.log(error.message)
          })

It takes too much time to fetch location

In some phones it gets into the loop and don't fetch the location.. Until you switch off and on the phone you cannot fetch the location .So please help in this regard.

Question: How to handle when user click outer modal ?

Hi, i'd like to ask, how to handle when user click outer moal ?, as i know if i click "OK" it take me to ".then" and if i click "CANCLE" it take me to ".catch". But how to handle if i not click both of that ?

thanks.

RuntimeException

Hi,
I'm getting the following errors:

`
java.lang.RuntimeException:
at android.app.ActivityThread.deliverResults (ActivityThread.java:4925)
at android.app.ActivityThread.handleSendResult (ActivityThread.java:4968)
at android.app.ActivityThread.access$1600 (ActivityThread.java:222)
at android.app.ActivityThread$H.handleMessage (ActivityThread.java:1849)
at android.os.Handler.dispatchMessage (Handler.java:102)
at android.os.Looper.loop (Looper.java:158)
at android.app.ActivityThread.main (ActivityThread.java:7229)
at java.lang.reflect.Method.invoke (Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)

Caused by: java.lang.RuntimeException:
at com.facebook.react.bridge.CallbackImpl.invoke (CallbackImpl.java:30)
at com.facebook.react.bridge.PromiseImpl.resolve (PromiseImpl.java:32)
at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.checkLocationService (LocationServicesDialogBoxModule.java:60)
at com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.onActivityResult (LocationServicesDialogBoxModule.java:90)

at com.facebook.react.bridge.ReactContext.onActivityResult (ReactContext.java:256)
at com.facebook.react.ReactInstanceManager.onActivityResult (ReactInstanceManager.java:601)
at com.facebook.react.ReactActivityDelegate.onActivityResult (ReactActivityDelegate.java:149)
at com.facebook.react.ReactActivity.onActivityResult (ReactActivity.java:77)
at com.demo.MainActivity.onActivityResult (MainActivity.java:23)

at android.app.Activity.dispatchActivityResult (Activity.java:7137)
at android.app.ActivityThread.deliverResults (ActivityThread.java:4921)

`
Devices: Galaxy J7, Galaxy S7 Edge
Android 6.0
compileSdkVersion: 23
buildToolsVersion: 25.0.2

No Activity found to handle Intent { act=android.settings.LOCATION_SOURCE_SETTINGS }

Fatal Exception: android.content.ActivityNotFoundException

OS: 6.0.1
Device: Ken Brown Neo Wise

Lib Version: 2.4.4

android.app.Instrumentation.checkStartActivityResult (Instrumentation.java:1798)
android.app.Instrumentation.execStartActivity (Instrumentation.java:1512)
android.app.Activity.startActivityForResult (Activity.java:3945)
android.app.Activity.startActivityForResult (Activity.java:3905)
com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.newActivity (LocationServicesDialogBoxModule.java:122)
com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.access$000 (LocationServicesDialogBoxModule.java:13)
com.showlocationservicesdialogbox.LocationServicesDialogBoxModule$2.onClick (LocationServicesDialogBoxModule.java:95)
com.android.internal.app.AlertController$ButtonHandler.handleMessage (AlertController.java:163)
android.os.Handler.dispatchMessage (Handler.java:102)
android.os.Looper.loop (Looper.java:148)
com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run (MessageQueueThreadImpl.java:194)
java.lang.Thread.run (Thread.java:818)

any ideas?
Thanks in advance!

How to know when GPS was enabled?

I want to know how to check if the gps was enabled by the user after the displayed dialog or before.

I mean, using you method there could be 2 stages:

LocationServicesDialogBox.checkLocationServicesIsEnabled({
            message: "",
            cancel: "",
            ok: ""
        })  
        .then(function (success) {})
        .catch((error) => {  });
  1. If the GPS is enabled (before showing the dialog) calling your method will return success
  2. If the GPS is disabled (before showing the dialog) calling your method will return succes if and only if the user enable the GPS in the prompted interface

Why I need this?
I have a button. If it is pressed and the GPS is disabled I show a dialog, and if the user enable the GPS in the prompted interface I dont want to continue the process instead the user has to click the button again.

In the case the GPS is enabled then there is no any dialog to show.

I don't know if you understand what I'm trying to say.

PD: I don't know if this article could be useful. In my case I don't know how to do what it says
https://stackoverflow.com/questions/41795968/react-native-check-and-promp-user-to-enable-network-gps/42002015#42002015

How can I achieve this?

Error in using other modules.

Added this to project and it is working fine but getting this error when using other modules ex react-native-image-picker

The callback checkLocationServicesIsEnabled() exists in module LocationServicesDialogBox, but only one callback may be registered to a function in a native module.

Illegal callback invocation from native module

Hi I am using react-native-android-location-services-dialog-box and getting the below exception

Fatal Exception: java.lang.RuntimeException Illegal callback invocation from native module. This callback type only permits a single invocation from native code. arrow_right com.facebook.react.bridge.CallbackImpl.invoke (CallbackImpl.java:30) com.facebook.react.bridge.PromiseImpl.reject (PromiseImpl.java:70) com.facebook.react.bridge.PromiseImpl.reject (PromiseImpl.java:54) com.showlocationservicesdialogbox.LocationServicesDialogBoxModule.forceCloseDialog (LocationServicesDialogBoxModule.java:45)

Could not find support-v4.jar (com.android.support:support-v4:26.1.0).

i just upgrade to react native 0.56.0 then i found this error.

`Could not resolve all files for configuration ':react-native-android-location-services-dialog-box:debugCompileClasspath'.

Could not find support-v4.jar (com.android.support:support-v4:26.1.0).
Searched in the following locations:
https://jcenter.bintray.com/com/android/support/support-v4/26.1.0/support-v4-26.1.0.jar
`

my current project:

  • React 16.3.1
  • React-Native 0.56.0
  • react-native-android-location-services-dialog-box 2.6.0

There is no update for react native 0.56.0 ? cause could not find also in jcenter

The callback checkLocationServicesIsEnabled() exists in module LocationServicesDialogBox but only one callback may be registered to a function in a native module

Hello
So I was using your module (1.1.8) along with several other native modules (namely react-native-image-picker and react-native-image-resizer) and when I ran a native function on that module (ImagePicker.launchImageLibrary({}, (response) => {}), I kept getting this error.

The callback checkLocationServicesIsEnabled() exists in module LocationServicesDialogBox but only one callback may be registered to a function in a native module

According to here, http://stackoverflow.com/questions/40785625/only-one-callback-may-be-registered-to-a-function-in-a-native-module-react-nativ , a registered callback could only be called once and for some reason calling the other native function causes the function in this module to run again, causing the callback to be called twice. So I tried placing a boolean to track whether the code has run once or not and that seemed to fix the problem.

class LocationServicesDialogBoxModule extends ReactContextBaseJavaModule implements ActivityEventListener {
...
private Boolean hasRun = false;
...
private void checkLocationService(Boolean activityResult) {
        // Robustness check
       if (currentActivity == null || map == null || promiseCallback == null || hasRun) return;
       ...
      hasRun = true;
}
...
}

Not sure whether this is right place to post this or whether the problem is in this module, but just thought of putting this out there.

Also here is the specific code related to this issue
index.android.js

getLocation(){
    LocationServicesDialogBox.checkLocationServicesIsEnabled({
      message: "<h3>Location off</h3> Around needs your location to continue. Would you like to turn on Location?",
      ok: "YES",
      cancel: "NO"
    }).then(success => {
      navigator.geolocation.getCurrentPosition(position => {
        var user = this.state.user;
        user.location = {
            lat: position.coords.latitude,
            lon: position.coords.longitude
        }
        this.setState({user, triedLocation: true});
      }, error => {
        this.setState({triedLocation: true, isLoading: false});
      }, {
        enableHighAccuracy: true,
        timeout: 20000
      })
    }).catch(error => {
      this.setState({triedLocation: true, isLoading: false});
    })
  }

addPost.js

import ImagePicker from 'react-native-image-picker';
import ImageResizer from 'react-native-image-resizer';
...
addAttachment(){
		ImagePicker.launchImageLibrary({}, (response)  => {
			if(response.didCancel){
				return;
			}
			if(response.error){
				ToastAndroid.show('An error occurred while selecting photo');
				return;
			}

			ImageResizer.createResizedImage(response.uri, 1000, 500, 'JPEG', 80).then((attachment)=>{
				this.setState({attachment})
			});
		});
}

get error when location is on

Looks like the app doesn't have the permission to access location. Add the following line to your app's AndroidManifest.xml:

LocationServicesDialogBoxModule is not abstract and does not override abstract method onActivityResult(int,int,Intent) in ActivityEventListener

I'm using RN 0.26.0 and after installing "react-native-android-location-services-dialog-box" I got this error

...\showlocationservicesdialogbox\LocationServicesDialogBoxModule.java:12: error: LocationServicesDialogBoxModule is not abstract and does not override abstract method onActivityResult(int,int,Intent) in ActivityEventListener
class LocationServicesDialogBoxModule extends ReactContextBaseJavaModule implements ActivityEventListener {
^
C:\RN\1\node_modules\react-native-android-location-services-dialog-box\android\src\main\java\com\showlocationservicesdialogbox\LocationServicesDialogBoxModule.java:22: error: method does not override or implement a method from a supertype
@OverRide
^
C:\RN\1\node_modules\react-native-android-location-services-dialog-box\android\src\main\java\com\showlocationservicesdialogbox\LocationServicesDialogBoxModule.java:77: error: method does not override or implement a method from a supertype
@OverRide
^
3 errors
FAILED

FAILURE: Build failed with an exception.

Unable to fetch location

Hi,
As you advised I have tried setting enableHighAccuracy to FALSE, even then most of the time it goes to error than success. It is not at all working properly in One PLUS phones and Mi Phone. Please help me in this regard...

Calling a method

If i call another method inside a .then(success) then state is not changing because that method is not calling. Please tell me how to call any method from inside .then(success)

Feature Request: Event Listener

Hi @webyonet first of all, thank you for this great plugin. I'm requesting if you can have a listener that listens when the user turns off their location service because as of now you have to call the function first before triggering the dialog. In my use case it should be triggered whenever the user turns off their location service. Thanks!

Just a nice message

I just wanted to thank you for this project. Easy to set up, use, and efficient. Thanks!

Crash when press the hardware back

The app will crash scenarios:

  1. Click the no button and click hardware back
  2. Click hardware back to close the dialog, and click hardware back again.

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.