geolocation.getCurrentPosition() not working in Android mobiles - ionic4

geolocation.getCurrentPosition() is not working in Android mobiles, is this an Ionic bug? Or is there any better solution to achieve this?
ngOnInit() {
this.geolocation.getCurrentPosition().then((resp) => {
}).catch((error) => {
console.log('Error getting location', error);
});
let watch = this.geolocation.watchPosition();
watch.subscribe((data) => {
this.data = data;
this.currentLat = data.coords.latitude;
this.currentLng = data.coords.longitude;
this.accuracy = data.coords.accuracy;
});
}

I had this issue once and was able to solve it by enabling High Accuracy GPS on the mobile device.
You can use the Location Accuracy Plugin
https://ionicframework.com/docs/native/location-accuracy
to activate high accuracy mode when loading the application
import { LocationAccuracy } from '#ionic-native/location-accuracy/ngx';
constructor(private locationAccuracy: LocationAccuracy) { }
...
this.locationAccuracy.canRequest().then((canRequest: boolean) => {
if(canRequest) {
this.locationAccuracy.request(this.locationAccuracy.REQUEST_PRIORITY_HIGH_ACCURACY).then(
() => console.log('Request successful'),
error => console.log('Error requesting location permissions', error)
);
}
});
or you can simply pass
this.geolocation.getCurrentPosition({ enableHighAccuracy : true, timeout: 10000 } )

Try setting the next values in the variable options
import { Geolocation, Geoposition } from '../../node_modules/#ionic-native/geolocation';
constructor(private geolocation: Geolocation)
...
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
this.geolocation.getCurrentPosition(options)
.then((result: Geoposition) => {
console.log(result)
})
.catch(error => {
console.error(error)
})
});

Related

How to use react native track player to stream live audio

Hello I have a streaming service, (it is an online radio) that I need to stream in my app, the url it is the following
https://cast.uncuartocomunicacion.com:8020/live
I have been using react native sound player to stream it but I had issues with android's performance. So I switched to react native track player, but I haven't been able of playing the streaming service.
the following it is the code I have been using.
const start = async () => {
await TrackPlayer.setupPlayer();
await TrackPlayer.add({
id: 'trackI1',
url: 'https://cast.uncuartocomunicacion.com:8020/live',
title: 'Area deportiva',
artist: 'Area deportiva',
artwork: {
uri:
'https://pbs.twimg.com/profile_images/1480935488232075270/STi9FaUo_400x400.jpg',
},
});
TrackPlayer.updateOptions({
stopWithApp: false,
});
setLoading(false);
};
useEffect(() => {
//let isMounted = true;
//Alert.alert(audioUrl);
//getUrl();
//SoundPlayer.loadUrl('https://cast.uncuartocomunicacion.com:8020/live');
/*TrackPlayer.setupPlayer()
.then(() => {
setLoading(false);
})
.catch((e) => {
setLoading(false);
});*/
start()
.then()
.catch((e) => {
Alert.alert('e ' + JSON.stringify(e));
});
}, []);
const handlePlayPause = () => {
console.warn('asa is playing ', isPlaying);
/* */
try {
/* !isPlaying ? SoundPlayer.resume() : SoundPlayer.pause();*/
if (!isPlaying) {
Alert.alert('enre aquiu ');
TrackPlayer.play()
.then((r) => {
Alert.alert('then play' + JSON.stringify(r));
})
.catch((e) => {
Alert.alert('e ' + JSON.stringify(e));
});
} else {
TrackPlayer.pause().then((r) => console.log(r));
}
} catch (e) {}
setIsPlaying(!isPlaying);
};
I hope someone can help me!!!
For some reason when you play audio with SSL and use another port (8020) it doesn't work, but you can try using http and add
android:usesCleartextTraffic="true"
in AndroidManifest

bleManager.startDeviceScan not working on iOS react-native-ble-plx

I am trying to pair a gateway to React native app using the react-native-ble-plx.
The below source code works fine in Android wheras in iOS, the bleManager.startDeviceScan() is not triggered. Nothing happens after this step.
Any help is much appreciated!
Source code:
const connectBLE = () => {
const subscription = bleManager.onStateChange(async (state) => {
if (state === 'PoweredOn') {
subscription.remove();
scanAndConnect();
}
};
}
const scanAndConnect = () => {
bleManager.startDeviceScan(null, null, async (error, device) => {
if (error) {
showToast(error, 'error');
console.log('Handle error - scanning will be stopped automatically');
return;
}
console.log('Devices');
console.log(device.name);
// Check if it is a device you are looking for based on device name
if (device.name === "BLE_0006") {
// Stop scanning as we have found the device.
bleManager.stopDeviceScan();
// Establish Device connection.
device
.connect()
.then((deviceData) => {
/** Show Toast on Device disconnect */
bleManager.onDeviceDisconnected(
deviceData.id,
(connectionError, connectionData) => {
if (connectionError) {
console.log(connectionError);
}
console.log('Device is disconnected');
console.log(connectionData);
},
);
/** Discover All Services and Characteristics */
return device.discoverAllServicesAndCharacteristics();
})
.then(async (deviceObject) => {
console.log('deviceObject');
console.log(deviceObject);
/** Subscribe for the Readable service */
device.monitorCharacteristicForService(
Enum.bleConnectionInfo.customServiceUUID,
Enum.bleConnectionInfo.readCharacteristicUUID,
(error, characteristic) => {
if (error) {
console.log('Error in monitorCharacteristicForService');
console.log(error.message);
return;
}
console.log(characteristic.uuid, characteristic.value);
]);
},
);
})
.catch((error) => {
console.warn(error);
showToast(error, 'error');
});
}
});
}
This might be helpful for someone!
The Issue was resolved by moving the bleManager() initialization outside the functional component.

How can I keep a socket connection alive in the background in React Native?

I use Wix navigation v2, socket.io-client, react-native-background-time and react-native v59.10
first I register a HeadlessTask in index.js
if (Platform.OS === 'android') {
AppRegistry.registerHeadlessTask(
'backgroundTask',
() => backgroundTask
);
}
then in backgroundTask.js
import BackgroundTimer from 'react-native-background-timer';
import io from 'socket.io-client';
import { showLocalPushNotification } from 'helper/PushNotificationServices';
const URL = 'http://SOME_SECURE_URL'; //:)
const currentTimestamp = () => {
const d = new Date();
const z = n => (n.toString().length == 1 ? `0${n}` : n); // Zero pad
return `${d.getFullYear()}-${z(d.getMonth() + 1)}-${z(d.getDate())} ${z(
d.getHours()
)}:${z(d.getMinutes())}`;
};
let socket = io(URL, {
reconnection: true,
reconnectionDelay: 1000,
reconnectionDelayMax: 5000,
reconnectionAttempts: Infinity,
autoConnect: true
});
socket.on('connect', () => {
showLocalPushNotification('Socket Say', `socket connect successfully`);
});
socket.on('disconnect', reason => {
console.log(reason);
socket.connect();
if (reason === 'io server disconnect') {
// the disconnection was initiated by the server, you need to reconnect manually
}
console.log('disconnect');
showLocalPushNotification('Socket Say', `socket disconnect :(`);
});
socket = socket.on('receive', async data => {
console.log('receive');
showLocalPushNotification(
'Socket Say',
`${currentTimestamp()}`
);
console.log(data);
});
socket.on('reconnect', attemptNumber => {
console.log('reconnect');
console.log(attemptNumber);
// ...
});
socket.on('reconnect_error', error => {
console.log('reconnect_error');
console.log(error);
// ...
});
socket.on('reconnect_failed', () => {
console.log('reconnect_failed');
// ...
});
BackgroundTimer.runBackgroundTimer(() => {
showLocalPushNotification(
'BackgroundTimer Say',
`${value || ''}\n${currentTimestamp()}`
);
socket.emit('send', { my: 'ok i get news' });
// this.socket.emit('send', { my: 'ok i get news' });
}, 1000 * 15 * 60);
in a real device, when the app goes to background, the socket will be disconnected after a while and I can't reconnect it again, how can I keep the connection alive?
I'm facing the same issue for long time, but I solved calling socket.connect() when I send app in background
AppState.addEventListener("change", this._handleAppStateChange.bind(this))
_handleAppStateChange(state) {
if (state == "background") {
socket.connect();
}
}

Gulp 4 keep watching even on error

How can I make this
// ...
gulp.watch(source.app, gulp.series(
lint(source.app),
transpile(source.app),
ATDD,
));
To keep watching even if error occurred from linter or transpiler?
My task function looks like this:
// ...
function lintWorker(source) {
return gulp.src(source)
.pipe(tslint({
configuration: "tslint.json",
options : {
formatter: "prose"
}
}))
.pipe(tslint.report(stylish, {
emitError: false,
sort: true,
bell: true
}));
};
export function lint(source) {
let fn = () => {
return lintWorker(source);
};
fn.displayName = ["linting", ...source].join(" ");
return fn;
};
I found the simple way how to do it.
gulp.watch(source.app, (done) => {
gulp.series(
lint(source.app),
transpile(source.app),
ATDD,
)((err) => {
if (err) {
console.error("error", err);
}
done();
});
});

How to start geolocation on firebaseAuth success

I'm using $firebaseAuth to control the login part of my application and I want to launch a geolocation when user is authenticate.
Geolocation start before the authentication when I use the code below :
.run(function($ionicPlatform, $rootScope, $location, Auth, $ionicLoading, $cordovaGeolocation, geoLocation, defautLocation) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
$rootScope.firebaseUrl = firebaseUrl;
$rootScope.displayName = null;
Auth.$onAuth(function (authData) {
if (authData) {
console.log("Logged in as:", authData.uid);
} else {
console.log("Logged out");
$ionicLoading.hide();
$location.path('/login');
}
})
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
...
}, function(err) {
...
});
$cordovaGeolocation.watchPosition({
frequency: 1000,
timeout: 3000,
enableHighAccuracy: false
}).then(function () {
}, function (err) {
...
});
$rootScope.logout = function () {
console.log("Logging out from the app");
$ionicLoading.show({
template: 'Logging Out...'
});
Auth.$unauth();
}
...
I try to wrap $cordovaGeolocation :
Auth.$requireAuth().then(function(authData) {
if (authData) {
$cordovaGeolocation
.getCurrentPosition()
.then(function (position) {
...
}, function(err){
...
});
$cordovaGeolocation.watchPosition({
frequency: 1000,
timeout: 3000,
enableHighAccuracy: false
}).then(function () {
}, function (err) {
...
});
}else{
...
}
});
But when user sign in it doesn't launch the geolocation, I need to reload.
watchPosition means my function have to be active all time during authentication.
So my question is, how I can execute my geolocation function just after the authentication success and until unAuth() ?
(I'm new on Angular and Firebase, no surprise)
Thx a lot,