React Native Geolocation Timed Out - android

I use geolocation to get the current location of users in my project. but I get the Timed Out Error error.
{TIMEOUT: 3, POSITION_UNAVAILABLE: 2, PERMISSION_DENIED: 1, message: "Location request timed out", code: 3}
API 28 android phone success,
API 21 android phone success,
API 23 android phone time out error.
All permission granted.
try{
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({
firstLat: position.coords.latitude,
firstLng: position.coords.longitude,
});
this.getLocation(position.coords.latitude, position.coords.longitude);
this.setState({
isLoading:true
})
},
error => console.log(error),
{enableHighAccuracy: true, timeout:10000, maximumAge:1000},
);
}catch (e) {
console.log(e)
}
AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
thank you.

Related

react native - crash the app when I call scan function with react-native-ble-manager

I used for the first time react-native-ble-manager.
The app has all the permissions, however when I run the BleManager.scan() the app is closing without any error or logs.
I know the code is a little ugly but it's just for testing, the first second I run the bluetooth manager start and after 5 seconds I run the scan.
But the crash happen immediately after 5 seconds.
Any idea why?
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
const handleDiscoverPeripheral = (peripheral) => {
console.log('Got ble peripheral', peripheral);
if (!peripheral.name) {
peripheral.name = 'NO NAME';
}
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
const handleStopScan = () => {
console.log('Scan is stopped');
}
let interval;
let gImageShow = true;
let gTime = 0;
BleManager.enableBluetooth()
.then(() => {
// Success code
console.log("The bluetooth is already enabled or the user confirm");
})
.catch((error) => {
// Failure code
console.log("The user refuse to enable bluetooth");
});
function App(props) {
const [shouldShow, setShouldShow] = useState(gImageShow);
useEffect(() => {
interval = setInterval(() => {
if (gTime == 1)
{
BleManager.start({showAlert: true});
bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan );
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
if (result) {
console.log("Permission is OK");
}
});
}
if (gTime == 5)
{
BleManager.scan([], 10, true);
}
gImageShow = !gImageShow;
setShouldShow(gImageShow);
gTime = gTime + 1;
},1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
});
the manifest is like:
xmlns:tools="http://schemas.android.com/tools"
package="com.diagnostic_ble">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>
<!-- Needed only if your app looks for Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
The problem has been solved. The new android 12 (I think from this one), needs a different permission that it hasn't been updated in react-native-ble-manager webpage.
In the manifest you need to add
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Also, In the app.js you need to call once requestPermissions();
that it can be like
const requestPermissions = async () => {
if (Platform.OS === 'android') {
const apiLevel = await DeviceInfo.getApiLevel();
if (apiLevel < 31) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'Bluetooth Low Energy requires Location',
buttonNeutral: 'Ask Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
} else {
const result = await requestMultiple([
PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
]);
const isGranted =
result['android.permission.BLUETOOTH_CONNECT'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.ACCESS_FINE_LOCATION'] ===
PermissionsAndroid.RESULTS.GRANTED;
}
} else {
}
};

React native image picker camera crashes

I am using image picker in react native but an error occurs:
file:///storage/emulated exposed beyond app through clipdata.item
On ios, the camera opens normally. and in android i can pick an image from gallery normally.
My code:
const selectFile = (itemI,inputValue) => {
let options = {
title: 'Select Image',
maxWidth:800,
maxHeight:800,
quality:0.2,
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true,
saveToPhotos:true
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log(
'User tapped custom button: ',
response.customButton
);
alert(response.customButton);
} else {
//let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
filePath[itemI]=source;
addItemCustom(" ");
}
});
};
I tried to add:
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
....
android:requestLegacyExternalStorage="true"
...>
but the error is the same.

React Native 0.66.* axios call [TypeError: Network request failed] ANDROID

Hi i am new in react native
i have macbook and i am running Laravel projects in macbook by using Laravel valet park
simple i am trying to generating Auth token by using any API which is developed in laravel 8. when i hit API by using postman then i got 100% response. but when i try to hit this API by using axios in react native always i am getting "NETWROK ERROR" in response.
import axios from 'axios';
axios.defaults.baseURL = 'http://cms.test/';
const LoginScreen = ({navigation}) => {
const [email,setEmail] = useState('');
const [password,setPassword] = useState('');
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const login = async() => {
if(!email || !password){
Alert.alert('Please fill all fields')
}else{
axios.post('api/token', {
email,
password,
device_name: 'mobile',
}, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
const userResponse = {
email: response.data.user.email,
token: response.data.token,
}
setUser(userResponse);
setError(null);
// SecureStore.setItemAsync('user', JSON.stringify(userResponse));
AsyncStorage.setItem('user', JSON.stringify(userResponse));
})
.catch(error => {
console.log(error);
return false;
const key = Object.keys(error.response.data.errors)[0];
setError(error.response.data.errors[key][0]);
})
}
}
Always getting "NETWORK ERROR" in response.
Note: i already updated AndroidManifest.xml file by these below linse
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
But there is not any change, still getting "NETWORK ERROR", on hit API
Some times android emulator get problem with network when your wifi network changed or reconnected re-run your emulator again.

API fetching in ReactNative

my name is Leo, I'm a newbie in Reactnative
I'm trying to make a login to my app and i met a problem with fetch API.
i recieved [TypeError: Network request failed]. I run on device API 30
here is my code:
const loginHadle = async(email, password)=>{
await fetch ('http://127.0.0.1:8000/login/',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"email": email, "password":password})
}).then(response=>{
if(response.status==200)
{
response.json().then(data=>{
signIn(data.email, data.tokens);
})
}
})
.then(res => {
console.log("reponse :", res);
}).catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
}
and I've already add this line to AndroidManifest.xml
android:usesCleartextTraffic="true"
here is what i receive on postman
Thank you very much!
On Android 9 because of the "http" and issue resolved by just adding android:usesCleartextTraffic="true" in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application android:usesCleartextTraffic="true"> . . . </application>

Geolocation and PubNub work on the browser but not on android

I have a code for my application (in which I am using Apache Cordova) in PubNube HTML5 JavaScript geolocation, which identifies the user's location in real time, however, this code works perfectly in the browser, but when I transform the file of Apache Cordova in APK by Android Studio, it ends up not working in APK, so I think it is easy to solve, since it is working on one platform and the other is not.
My Android Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.apache.cordova" android:versionName="1.0" android:versionCode="1">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_GPS" />
<uses-permission android:name="android.permission.ACCESS_ASSISTED_GPS" />
<uses-permission android:name="android.permission.ACCESS_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
My Javascript Code
const clientUUID = PubNub.generateUUID();
var pubnub = new PubNub({
publishKey: *****,
subscribeKey: ****,
secretkey: ****
});
if ('geolocation' in navigator) {
const watcher = navigator.geolocation.watchPosition(function(position){
// sets default position to your position
var latitude = position.coords["latitude"];
var longitude = position.coords["longitude"];
var altitude = 0;
console.log(position);
console.log({"lat":latitude, "lng":longitude, "alt":0});
var newMessage = {
lat: latitude,
lng: longitude
}
pubnub.publish(
{
channel: "******",
message: newMessage
},
function(status, response) {
console.log(status, response);
console.log("Submit");
console.log(newMessage);
}
);
}, function(error){
console.log(error)
}, {enableHighAccuracy: true, maximumAge: 30000, timeout: 30000})
}

Categories

Resources