Flutter : Check GPS Location Mode - flutter

I have project related using maps and tracking location user , for this i used Geolocator Package. I need to check current location of user , in my flow project first i check last position of user , if last position null then i check current position of user.
Code
Position _currentPosition;
Position get currentPosition => _currentPosition;
Future<void> getCurrentPosition() async {
try {
Position lastPosition = await Geolocator().getLastKnownPosition();
if (lastPosition != null) {
print("Success Get Last Position...");
_currentPosition = lastPosition;
} else {
final currentPosition = await Geolocator().getCurrentPosition();
if (currentPosition != null) {
print("Success Get Your Current Position...");
_currentPosition = currentPosition;
} else {
throw "Can't Get Your Position";
}
}
} catch (e) {
throw e;
}
notifyListeners();
}
Then i calling getCurrentPosition Function on my button OnPressed to get location user like this :
Button GetLocation
void goToMaps() async {
final mapsProvider = context.read<MapsProvider>();
try {
print('Get Location User');
await mapsProvider.getCurrentPosition();
print('Success Get location User');
} catch (e) {
globalF.showToast(message: e.toString(), isError: true, isLongDuration: true);
}
}
First Problem is , When GPS Location Mode is Device Only I can't get LastPosition or Current Position it never print Success Get Location User and still print Get Location User.
Second Problem is , When Gps Location Mode is Battery Saving user location i got is very inaccurate, compared i used mode High Accuracy.
My question is , How can i check if gps location mode != High Accuracy , then i can show warning user to set the gps to High Accuracy.
Similiar Like this question
Thank's.

For the second problem, it happens because in High Accuracy mode android uses both GPS and network location, but in Battery Saving mode GPS module is turned off. If it was native Android, you could check provider of the location if you get location from LocationManager. But provider is not available in Flutter in Position class. You can instead use accuracy. If it is greater than a threshold and not suitable for your application, you can suggest the user to turn on High Accuracy mode.
Another options would be to use other package than Geolocator (however I'm not aware of any package that provides necessary interface) or to modify source code of Geolocatior so that it provides information about which mode is currently active.

Related

Flutter app restarts every time while capturing image from camera on Android devices

Flutter app restarts every time while capturing image from camera. We have used image picker plugin for this. version : ^0.6.7+12.
This has been observed mostly in 2GB RAM devices. Please help with this issue. Thank you in advance.
I think this may happen due to low memory.
Handling MainActivity destruction on Android
Android system -- although very rarely -- sometimes kills the MainActivity after the image_picker finishes. When this happens, we lost the data selected from the image_picker. You can use retrieveLostData to retrieve the lost data in this situation. For example:
Future<void> retrieveLostData() async {
final LostData response =
await picker.getLostData();
if (response.isEmpty) {
return;
}
if (response.file != null) {
setState(() {
if (response.type == RetrieveType.video) {
_handleVideo(response.file);
} else {
_handleImage(response.file);
}
});
} else {
_handleError(response.exception);
}
}
MainActivity destruction on Android

Wrong device count after connecting a new device

I'm integrating Agora with Unity, and we have a device selection screen for the user to select and test their devices before joining a call.
The problem I'm having is that Agora is not detecting device changes accordingly in runtime, which won't let me update my UI to reflect these changes.
void Start()
{
// get Agora engine, should be initialized already in the AgoraIOController component
agoraEngine = GetComponent<AgoraIOController>().GetAgoraEngine();
agoraEngine.OnAudioDeviceStateChanged += DeviceChangedHandler;
InitializeDeviceManager();
}
...
void DeviceChangedHandler(string deviceId, int deviceType, int deviceState)
{
devicesDirty = true;
onDevicesChanged.Invoke();
}
...
void RefreshDeviceList()
{
devices.Clear();
int audioDeviceCount = audioDeviceManager.GetAudioPlaybackDeviceCount();
if (audioDeviceCount == (int)ERROR_CODE.ERROR_NOT_INIT_ENGINE)
{
Debug.LogError("Agora engine not initialized, can't refresh devices");
return;
}
else if (audioDeviceCount < (int)ERROR_CODE.ERROR_OK)
{
Debug.LogError($"Unknown error while trying to get devices. Error code: {audioDeviceCount}");
return;
}
Debug.Log($"Found {audioDeviceCount} audio devices.");
for (int i = 0; i < audioDeviceCount; i++)
{
string deviceName = null;
string deviceId = null;
int result = audioDeviceManager.GetAudioPlaybackDevice(i, ref deviceName, ref deviceId);
if (result != (int)ERROR_CODE.ERROR_OK)
{
Debug.LogError("Error when trying to get audio device");
continue;
}
devices.Add(new AgoraDevice()
{
deviceId = deviceId,
deviceName = deviceName,
type = MEDIA_DEVICE_TYPE.AUDIO_RECORDING_DEVICE
});
}
}
If I connect a new microphone and restart the application, it's detected as expected, but if I connect a new device in runtime, I get the event for agoraEngine.OnAudioDeviceStateChanged but when I refresh the device list, the device count and device info is not being updated, so my UI is not showing the new state accordingly.
This happens if I have one mic and I connect a second one, or if I have two mics and I disconnect one. In either case Agora is not reflecting these changes after the devices changed event.
I also tried refreshing the device list in the next frame, or adding a button to manually refresh the list, to check if there was some delay in Agora for doing that update, but it's not happening.
Without this feature we're gonna have lots of issues with clients, connecting new devices in runtime happens all the time and we need to make this software robust and support these scenarios.
Any help is greatly appreciated!
EDIT:
Releasing and recreating the device manager helped, and the device list is updated, but this looks really weird and I don't think that the API should be used like this.
void DeviceChangedHandler(string deviceId, int deviceType, int deviceState)
{
devicesDirty = true;
audioDeviceManager.ReleaseAAudioRecordingDeviceManager();
audioDeviceManager.CreateAAudioRecordingDeviceManager();
onDevicesChanged.Invoke();
}
Since you are testing with mic plug/unplug, did you intend to call AudioPlaybackDeviceManager instead of AudioRecordingDeviceManager in your first part of the code?

How to show current location indication

I'm using the Flutter SDK Version 4.3.1.0.
I get my location updates from the geolocator plugin and want to show the location on the HERE map. It correctly centers the map to the current location but there is no location indicator.
I currently use the following code. What else do I need?
void _showPosition(final GeoCoordinates coordinates) {
_mapView.mapScene.loadSceneForMapScheme(MapScheme.greyDay, (MapError error) {
if (error != null) {
print("Map scene not loaded. MapError: " + error.toString());
return;
}
_mapView.camera.lookAtPointWithDistance(coordinates, 1000);
});
}
I'm using the Flutter Channel beta, v1.17.0-3.4.pre
The HERE SDK for Flutter does not contain a pre-configured location indicator. You can easily create one by adding a circle item onto the map:
For this I would recommend using a MapPolygon that contains a GeoCircle shape. You can then also update the radius of the GeoCircle on the fly to indicate the current horizontal accuracy of the geolocator plugin.

Geolocator().getCurrentPosition vs StreamSubscription<Position> in flutter

I am currently using Geolocator().getCurrentPosition to get user current position... but when I am build an app.. I want to calculate the distance between user current location and her/his house (for example)... but since user can move everywhere and stop at some point.. I also want to calculate that new distance... so the route is like this..
Home= A
user first location= B
user second location= C (so user move from B to C)
I need to know the location from A to B and from A to C
...So what I want to ask is..is it enough to use only Geolocator().getCurrentPosition or am I need also use StreamSubscription<Position> to listen for user location changes?
here is my code...
Geolocator()
.getCurrentPosition(desiredAccuracy: LocationAccuracy.high)
.then((Position position) {
setState(() {
_first = position;
});
_distanceCalculation(_first.latitude, _first.longitude);
}).catchError((error) {
print(error);
});
if I need StreamSubscription<Position> to listen for user location changes how the way to apply StreamSubscription<Position> inside my code

How can I get a fake 'current location' when creating an IOS Map with Xamarin Studio and the iPhone Emulator?

Problem:
When using the Xamarin iPhone emulator, the current location is not getting set on the map.
Details:
I'm trying to plot my current location on a Map, in a sample iPhone app I'm learning with Xamarin Studio and the iPhone emulator.
I have the map displayed but there's no current location getting set.
I did get asked to use my Current Location (which I'm sure I said yes/ok to) .. but it keeps centering it in San Fran, near union square :(
When ever I run my emulato, I see this text pop up:
2013-10-22 09:27:45.018 MyApp [6018:1503] MonoTouch: Socket error while connecting to MonoDevelop on 127.0.0.1:10000: Connection refused
So i'm not sure if that has something to do with it?
Ok, so lets look at some code I've got.
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
map.MapType = MKMapType.Standard;
map.ShowsUserLocation = true;
map.ZoomEnabled = true;
map.ScrollEnabled = true;
map.DidUpdateUserLocation += (sender, e) => {
if (map.UserLocation != null)
{
CentreMapAtLocation(map.UserLocation.Coordinate.Latitude,
map.UserLocation.Coordinate.Longitude);
}
// User denied permission, or device doesn't have GPS/location ability.
if (!map.UserLocationVisible)
{
// TODO: Send the map somewhere or hide the map and show another message.
//CLLocationCoordinate2D coords = new CLLocationCoordinate2D(37.33233141,-122.0312186); // cupertino
//MKCoordinateSpan span = new MKCoordinateSpan(MilesToLatitudeDegrees(20), MilesToLongitudeDegrees(20, coords.Latitude));
//mapView.Region = new MKCoordinateRegion(coords, span);
}
};
private void CentreMapAtLocation(double latitude, double longitude)
{
CLLocationCoordinate2D mapCenter = new CLLocationCoordinate2D (latitude, longitude);
MKCoordinateRegion mapRegion = MKCoordinateRegion.FromDistance (mapCenter, 10000, 10000);
map.CenterCoordinate = mapCenter;
map.Region = mapRegion;
}
So it's nothing too crazy, IMO.
Anyone have any suggestions?
Have you tried setting the custom location within the simulator?
I tend to use a combination of the Custom Location setting and this tool when I need to verify locations within the iOs simulator. You won't need to make any changes to your code for this to work; it just pipes the set location into the location manager within iOs.
To my knowledge, the simulator does not support GPS or WiFi based location therefore it can't use your current location like a physical device. Perhaps someone else can clarify this.
For further information, see:
Set the location in iPhone Simulator
http://bencoding.com/2011/12/28/setting-you-location-in-the-ios-5-0-simulator/