Using https://github.com/MacKentoch/react-native-beacons-manager
Works lovely on iOS, however, on Android, after I begin ranging beacons, the beacon array shows up with nothing in it (there are 6 beacons next to me and they all show up on iOS).
Here's what I'm doing:
componentDidMount() {
// Start detecting all iBeacons in the nearby
Beacons.detectIBeacons();
Beacons.startRangingBeaconsInRegion('Estimotes', 'B9407F30-F5F8-466E-AFF9-25556B57FE6D').then((data)=>{
console.log(data);
}).catch((reason) => {
console.log(reason);
});
// Print a log of the detected iBeacons (1 per second)
DeviceEventEmitter.addListener('beaconsDidRange', (data) => {
console.log(data);
});
}
In my console, I get this:
{beacons: Array(0), uuid: "b9407f30-f5f8-466e-aff9-25556b57fe6d", identifier: "Estimotes"}
I left the UUID of the Estimotes as default so this should work. Using a Samsung Galaxy S8+ for testing. Am I doing anything wrong coding wise here? Are there additional permissions on Android that I am missing? Bluetooth and Location services are on.
Alright, I figured it out. Newer versions of android require additional permissions. In your Manifest, throw this guy in there:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
.... if you're using react-native-kontaktio (which is better than react-native-beacons-manager imo) you'll also need to throw this in your Manifest in the <application> section:
<service android:name="com.kontakt.sdk.android.ble.service.ProximityService"/>
Then in your app.js you'll need to request the permission like () make sure you
import PermissionsAndroid
from 'react-native'
:
componentDidMount() {
try {
const granted = PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location Permission',
'message': 'Activeev needs to access your location.'
}
)
console.log('here', granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("Location Permitted")
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
}
Working like a charm now. Hope this helps someone else.
Thank you for your answer. It definitely worked. Based on your answer, below is my implementation.
import React, { Component } from 'react';
import { View, DeviceEventEmitter, ListView , Text} from 'react-native';
import Beacons from 'react-native-beacons-manager';
import {PermissionsAndroid} from 'react-native'
export default class App extends Component {
async componentDidMount() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location Permission',
'message': 'Activeev needs to access your location.'
}
)
console.log('here', granted);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("Location Permitted")
// Start detecting all iBeacons in the nearby
Beacons.detectIBeacons();
Beacons.startRangingBeaconsInRegion('test', '85d37dd8-a9dc-48a8-ab1c-b86fcb7a6a17').then((data)=>{
console.log(data);
})
.catch((reason) => {
console.log(reason);
});
// Print a log of the detected iBeacons (1 per second)
DeviceEventEmitter.addListener('beaconsDidRange', (data) => {
console.log(data);
});
} else {
console.log("Location permission denied")
}
}catch (err) {
console.warn(err)
}
}
render(){
return(
<View></View>
);
}
}
Related
I would like to permit my application to use Activity Recognition and how is it possible? I've tried something like this.
In my app.json, I added below based on Expo docs
"permissions": [
"com.google.android.gms.permission.ACTIVITY_RECOGNITION",
"ACTIVITY_RECOGNITION"
],
Then I am trying to make it appear by:
import { PermissionsAndroid } from 'react-native';
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACTIVITY_RECOGNITION,
{
title: "testtitle",
message:"testmessage",
buttonNeutral: "testbtn1",
buttonNegative: "testbtn2",
buttonPositive: "testbtn3",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("success");
} else {
console.log("denied");
}
} catch (err) {
console.warn(err);
}
Doing the above method doesn't work. How can I prompt it to the user? Thanks in advance.
I have troubles having audio permissions to work on android build. It works fine in expo go, but not in android build.
In the given code, the permission for the camera is asked properly, but when accepted the permission for audio shows only for a fraction of a second and return a not granted status.
Once again, it works fine in expo go.
Is there anything i’m doing wrong ? do you have an idea on how to solve this ?
Thanks you very much community !
SDK Version: 41
Platforms(Android/iOS/web/all): Android (samsung A20e)
import {Camera} from 'expo-camera'
import {Audio} from 'expo-av';
export default () => {
return (
<View>
<Button
onPress={() => {
Camera.requestPermissionsAsync().then((status) => {
// audio permission request is only shown for half a second in build mode and is automatically denied permission
Audio.requestPermissionsAsync().then((status) => {
console.log('ok');
});
});
}}>
Test
</Button>
</View>
);
};
Use it like this
Working Example Here
import { Camera } from 'expo-camera';
import { Audio } from 'expo-av';
const GetPermissions = async () => {
try {
console.log('Requesting permissions..');
const CameraPerm = await Camera.requestPermissionsAsync();
if (CameraPerm.status === 'granted') {
console.log('Camera Permission Granted');
}
const AudioPerm = await Audio.requestPermissionsAsync();
if (AudioPerm.status === 'granted') {
console.log('Audio Permission Granted');
}
} catch (err) {
console.error('Failed to get permissions', err);
}
};
return (
<View style={styles.container}>
<Button title="Get Permissions" onPress={GetPermissions} />
</View>
);
Make sure all the imports are correct
be sure to have either both or none in your app.json
that was my problem !
code
import RNFetchBlob from 'rn-fetch-blob';
RNFetchBlob.android
.actionViewIntent(
'/storage/emulated/0/Android/data/aaa.bbb.ccc/files/184.apk',
'application/vnd.android.package-archive',
)
.then(() => {
console.log('success');
})
.catch(err => {
console.log('error');
});
In the simulator, the above code works normally, and pops up the installation APK interface
On the phone (Android 8.1), the screen flashed white, then there was nothing, and the installation interface could not pop up, No error message
you should add permission in the AndroidMainFest.xml:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
but because it is dynamic permission, I suggest you every time before you download and install APK to check it if it has permission.
In this situation, you can write a native module, for dynamic check permission you can see this answer after it goes to the permission set page
you can also use the react-native-permission library.
requestInstallUpdate = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.REQUEST_INSTALL_PACKAGES,
{
'title': 'Test App',
'message': 'Test App needs to install updates.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can now install updates")
return true;
} else {
console.log("App install permission denied")
return false;
}
} catch (err) {
console.warn(err)
return false;
}
}
then in your download method
let canInstall = await requestInstallUpdate()
if(canInstall){
//download apk
}
Found out the reason for this, it's a know bug of the library and has a PR waiting to be merged (no timeframe from the repo owner). Here is the link to the PR: https://github.com/joltup/rn-fetch-blob/pull/317
So basically this needs to be added to line 122-123 of file android/src/main/java/com/RNFetchBlob/RNFetchBlob.java:
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
If above is not working do to the below step: overwrite the 121 line in android/src/main/java/com/RNFetchBlob/RNFetchBlob.java:
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // 121 line
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // 122 line
I have an app which developed in react-js. I want to integrate this app into react-native-webview. everything I right but I have two problems.
1-how can I access current location of the user in react-native-webview.
2-how can I debug my react-js(webpage) app inside react-native-webview.
for first problem
if I run webpage in a mobile browser and click on that event I'm getting current location of the user and at the same time when my react-native app getting started, I'm invoking permission for current location so in react-native-debugger i'm getting current location of user.i followed the similar example but this is related to react-native.
exact problem is how can I access the current location of webview in react-native-webview
for second problem
when I'm clicking on the event to fetch current location it is not showing the current location so ** I want to see what is error/response of that event**. because it is in webview I can access react-native logs in react-native-debugger but cannot see the web view logs in the debugger.I followed this one also but I don't know where to put that android config code.
my react-native code
import React, {Component} from 'react';
import {PermissionsAndroid} from 'react-native';
import { WebView } from "react-native-webview";
export default class App extends Component {
constructor(props){
super(props);
// To see all the requests in the chrome Dev tools in the network tab.
XMLHttpRequest = GLOBAL.originalXMLHttpRequest ?
GLOBAL.originalXMLHttpRequest :
GLOBAL.XMLHttpRequest;
// fetch logger
global._fetch = fetch;
global.fetch = function (uri, options, ...args) {
return global._fetch(uri, options, ...args).then((response) => {
console.log('Fetch', { request: { uri, options, ...args }, response });
return response;
});
};
}
async requestLocationPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Location Access Permission',
'message': 'Stanplus would like to use your location ' +
'so you we track you.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location");
if (typeof window !== 'undefined' && typeof window.navigator !== 'undefined' && navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
(position) => {
console.log(position.coords.latitude,'success');
},
(error) => {
console.log(error,'fail')
},
{ enableHighAccuracy: false, timeout: 5000, maximumAge: 10000 }
);
}
} else {
console.log("Location permission denied")
}
} catch (err) {
console.warn(err)
}
}
componentDidMount() {
this.requestLocationPermission();
}
render() {
return (
<WebView
source={{uri: 'https://3fa4f958.ngrok.io/steptwo'}}
style={{marginTop: 20}}
onMessage={(event)=> console.log(event.nativeEvent.data)}
scalesPageToFit={true}
javaScriptEnabled = {true}
/>
);
}
}
my React.js code which accesses current location
if (navigator.geolocation) {
alert('event clicked');//in react-native app its showing the alert
navigator.geolocation.getCurrentPosition(
//but inside here react-native can't execute because of location permission issue
position => {
let latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
let geocoder = new window.google.maps.Geocoder();
//do other stuff----------
}
)
}
** I want to fetch current location when user click on webpage event inside react-native app and how to debug webview code**
please help stuck since 2 days ):
A few steps are needed to get it working on Android.
Add this line to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
And then in your app you'll need to request location once before the webview can request it. Do it like so in your view:
import { PermissionsAndroid } from 'react-native';
...
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Access Permission',
message: 'We would like to use your location',
buttonPositive: 'Okay'
}
);
And then also on your webview add the property:
geolocationEnabled={true}
you need to add geolocationenabled https://facebook.github.io/react-native/docs/webview#geolocationenabled
I have been trying to use React Native 's GeoLocalisation for an Android App. The poorly documentated module is found here https://facebook.github.io/react-native/docs/geolocation.html.
According to the documentation, you handle location permissions on Android using the following code in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, my online research suggests that the above line of code is useless for versions of ANDROID >= 6.0
As my implementation of GeoLocation is not currently working, I have no other reason but to believe that location permissions are not correctly handled.
How do I successfully request location permission at run-time for React Native Android App?
I solved it by changing the targetSdkVersion ( same to compileSdkVersion, in my case 23) in android/app/build.gradle.
Edit AndroidManifest.xml located in android/src/main and add the
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
next :
import { PermissionsAndroid } from 'react-native';
and then add this method:
export async function requestLocationPermission()
{
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Example App',
'message': 'Example App access to your location '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location")
alert("You can use the location");
} else {
console.log("location permission denied")
alert("Location permission denied");
}
} catch (err) {
console.warn(err)
}
}
and access the method when you request the location at run-time
async componentWillMount() {
await requestLocationPermission()
}
This did not work for me
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
}
I referred to https://facebook.github.io/react-native/docs/permissionsandroid.html#request
and check() return a boolean
const granted = await PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION );
if (granted) {
console.log( "You can use the ACCESS_FINE_LOCATION" )
}
else {
console.log( "ACCESS_FINE_LOCATION permission denied" )
}
You could use the react native PermissionsAndroid to request the permission: https://facebook.github.io/react-native/docs/permissionsandroid.html#request
Or, an easier option will be using a library that does it for you, such as https://github.com/yonahforst/react-native-permissions
I've noticed two things:
You have to change compileSdkVersion 23 in build.gradle file
You have to add your View's click listener to display to Permission dialog.
Sample code:
import React, { Component } from 'react';
import { Text, PermissionsAndroid, Alert } from 'react-native';
export default class RuntimePermissionSample extends React.Component {
constructor(props) {
super(props);
}
async requestLocationPermission() {
const chckLocationPermission = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
if (chckLocationPermission === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Cool Location App required Location permission',
'message': 'We required Location permission in order to get device location ' +
'Please grant us.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
alert("You don't have access for the location");
}
} catch (err) {
alert(err)
}
}
};
render() {
return (
<Text
onPress={() => this.requestLocationPermission()}>
Request Location Permission
</Text>
)
}
}
Hope this would help you.
You can ask location permission using following code
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You can use the location")
} else {
alert("Location permission denied")
}
} catch (err) {
console.warn(err)
}
alert('hi');
in Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
more details
import {PermissionsAndroid} from 'react-native';
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Cool Photo App Camera Permission',
message:
'Cool Photo App needs access to your camera ' +
'so you can take awesome pictures.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can use the camera');
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
}
export default class AlertDetails extends Component{
async componentDidMount() {
await request_storage_runtime_permission()
}
}