How to get the Latitude and Longitude when GPS is not Available? - android

I have implemented an android application using GoogleApiClient which sends the Location updates after every 5m displacement and it is working fine.
Consider sometimes will not get Gps Signal.In such situation how can we get the update can anyone please help me how to handle this situation?

try this,
Location nwLocation = appLocationService
.getLocation(LocationManager.NETWORK_PROVIDER);
if (nwLocation != null) {
double latitude = nwLocation.getLatitude();
double longitude = nwLocation.getLongitude();
Toast.makeText(
getApplicationContext(),
"Mobile Location (NW): \nLatitude: " + latitude
+ "\nLongitude: " + longitude,
Toast.LENGTH_LONG).show();
}
the complete tutorial can be found here

please have a look this link.
and i used this code to fetch lat long:
public void getCurruntLocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
and
private class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
latLng = location.getLatitude() + "," + location.getLongitude();
Toast.makeText(RecentActivity.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
and simple call getCurruntLocation() where you want to fetch.

GoogleApiClient uses a LocationRequest class for setting number of parameters. One of them - .setPrioryty. If you are using LocationRequest.PRIORITY_HIGH_ACCURACY in some cases googleApiClient won't call onLocationChanged() without gps, due to lack of accuracy of GPRS coordinates.

Related

How to use Geolocation API of google on itel A16 device?

I have trouble getting latitude and longitude on Itel A16 device (Android 8.1.0). I have used the following code, which works fine based on my test on other devices and emulators. But not on Itel A16 I would appreciate any help to fix this so that the Toast can show device location.
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getContext().LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double MyLat = location.getLatitude();
double MyLong = location.getLongitude();
Toast.makeText(getContext(), " latitude: " + MyLat + " longitude: " + MyLong, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Location test
if (checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
I fixed the issue with FusedLocationProviderClient , following Android Developers instructions

GPS Locations only from network

I am getting locations from network only not gps.i need gps locations not network provider..but as i see in my logfile..i am only getting network location which are not accurate.so i need to have gps locations..please help me out where i am doing wrong.thanks in advance..
if(isNetworkEnabled)
{
try
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0,
ll = new LocationListener() {
public void onLocationChanged(Location loc)
{
try {
location = loc;
latitude = location.getLatitude();
longitude = location.getLongitude();
logFile log=new logFile();
dt = location.getTime();
log.createFile("Location Changed NETWORK:"+latitude+""+longitude+"time:"+dt);
setdateAndtime(dt);
} catch (Exception e) {
String errMsg= e.getClass().getName() + " " + e.getMessage();
logFile log=new logFile();
log.createFile("Error in GPS TRACKER When Location Changed"+errMsg+"\n");
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
dt = location.getTime();
setdateAndtime(dt);
logFile log=new logFile();
log.createFile("Location From NETWORK:" + latitude + " " + longitude +
"time:" + dt + ":" + location.getProvider() + location);
}
}
catch(Exception e)
{
System.out.println(e+"Error MSg");
}
}
if(isGPSEnabled)
{
try
{
if (location != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0,
ll = new LocationListener() {
public void onLocationChanged(Location loc)
{
try {
location = loc;
latitude = location.getLatitude();
longitude = location.getLongitude();
logFile log=new logFile();
dt = location.getTime();
log.createFile("Location Changed GPS:"+latitude+""+longitude+"time:"+dt);
setdateAndtime(dt);
} catch (Exception e) {
String errMsg= e.getClass().getName() + " " + e.getMessage();
logFile log=new logFile();
log.createFile("Error in GPS TRACKER When Location Changed"+errMsg+"\n");
}
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status,
Bundle extras) {}
});
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
dt = location.getTime();
setdateAndtime(dt);
logFile log=new logFile();
log.createFile("Location From GPS:" + latitude + " " + longitude +
"time:" + dt + ":" + location.getProvider() + location);
}
Change order and conditions.
Your code is..
if (enable_network)
{
// get location from network provider
}
if (enable_gps)
{
// get location from gps provider
}
Your code always receive location from network provider(if it was on).
So, you should check gps provider condition first and check network provider next.
Change code like this
if (enable_gps)
{
// get location from gps provider
}
else (enable_network)
{
// get location from network provider
}
else
{
// can not receive location data
}
I things your testing your application in the Indoor,As the GPS does not work in indoor and that why it is working with your network...try to check the application by moving outside...
Avinash I believe you are from India. Why is that important? because in India even on outside I was not able to get the location from GPS via LocationManager I have ran so many tests on GPS from LocationManager. It seems to return location very rarely from GPS provider.
Solution
Use LocationClient (Google Play services) to retrieve the current location. Google play services are very accurate and retrieves location from Network, GPS and Wifi, If available.
And there are more chances that you can Location. Follow this guide

How to get current GPS position without waiting for location change on Android?

I want to get the current location of the device using the gps provider, but this actually waits for the gps position to change.
So I have a simple application that listens for the location change. This works with NETWORK_PROVIDER instantly, but for GPS_PROVIDER I waited for 15 minutes and no action has occured.
I'm using API level 8.
public class MainActivity extends Activity {
TextView tv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) this.findViewById(R.id.textView1);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new mylocationlistener();
//lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, ll); // this works fine
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
}
private class mylocationlistener implements LocationListener {
public void onLocationChanged(Location location) {
Date today = new Date();
Timestamp currentTimeStamp = new Timestamp(today.getTime());
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + "");
Log.d("LOCATION CHANGED", location.getLongitude() + "");
String str = "\n CurrentLocation: " + "\n Latitude: "
+ location.getLatitude() + "\n Longitude: "
+ location.getLongitude() + "\n Accuracy: "
+ location.getAccuracy() + "\n CurrentTimeStamp "
+ currentTimeStamp + "\n Altitude: "
+ location.getAltitude() + "\n Bearing"
+ location.getBearing() + "\n Speed"
+ location.getSpeed() + "\n ";
Toast.makeText(MainActivity.this, str, Toast.LENGTH_LONG)
.show();
tv.append(str);
}
}
public void onProviderDisabled(String provider) {
Toast.makeText(MainActivity.this, "Error onProviderDisabled",
Toast.LENGTH_LONG).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(MainActivity.this, "onProviderEnabled",
Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(MainActivity.this, "onStatusChanged",
Toast.LENGTH_LONG).show();
}
}
}
I did put the permission in the manifest, so this is not the problem.
Are you testing inside? Unless you are outside, you may not get a GPS lock at all, which will mean that the phone will attempt to get a lock as often as it can (as you have specified 0 and 0 for the minimum time and distance in your requestLocationUpdates call).
Unfortunately, you just have to wait for the device to get a GPS lock, and if it doesn't because of a lack of signal, you'll just keep waiting. The first thing you can do to alleviate this is to try to get the last known location for the GPS provider. This will return a location if the device recently had a GPS lock and stored a location:
Location lastLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Other than that, you should just try to get the location from the network provider, since that is likely to return a location much quicker than GPS, as you have already observed. This is because of the abundance of sources of location data (cell towers and WIFI), that are available everywhere, including indoors, as long as you have a wireless signal.
try{
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Location location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String stlongitude = Double.toString(longitude);
String stlatitude = Double.toString(latitude);
TextView celllocation = (TextView) findViewById(R.id.txtCellLocation);
celllocation.setText(stlatitude + " , " + stlongitude);
//String uri = String.format(Locale.ENGLISH, "geo:%f,%f", latitude, longitude);
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
//startActivity(intent);
}
catch (Exception a) {
LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double longitude = location.getLongitude();
double latitude = location.getLatitude();
String stlongitude = Double.toString(longitude);
String stlatitude = Double.toString(latitude);
TextView celllocation = (TextView) findViewById(R.id.txtCellLocation);
celllocation.setText(stlatitude + " , " + stlongitude);
}

android:I can not stop GPS update

My app find out current location using GPS. It is working fine in outdoor. But where GPS is not available or poor it is trying to get update again and again and it drains battery. So i want to stop update when GPS is poor or unavailable. You may suggest to use
lm.removeUpdates(locationlistenerforGPS);
It is working fine when GPS is available not in indoor. I like to stop update when GPS is poor or unavailable.
my code is
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationlistenerforGPS = new mylocationlistenerGPS();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationlistenerforGPS);
My locationlistenerGPS() function is
private class mylocationlistenerGPS implements LocationListener {
#Override
public void onLocationChanged(Location location) {
counterGPS++;
if (location != null) {
Log.d("LOCATION CHANGED", location.getLatitude() + " ");
Log.d("LOCATION CHANGED", location.getLongitude() + " ");
Toast.makeText(LocationActivity.this,"latitude: "+
location.getLatitude() + "longitude: " + location.getLongitude()
+ " Provider:" + location.getProvider() + " Accuracy:" + location.getAccuracy(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Thank you very much for any kind of assistance.
Don't use minTime and minDistance set to zero in requestLocationUpdates(). See requestLocationUpdates() documentation.
Bundle extras in onStatusChanged() may include satellites - the number of satellites used to derive the fix, this way you can define poor signal or you can use NmeaListener if you need additional information from GPS.

Current location of user is not finding using GPS Provider

I am using the following code to find current location of user
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
public void onLocationChanged(Location location) {
Log.e("changed","location");
// TODO Auto-generated method stub
showLocation(location);
}
But the location of user is not finding.If i change provider to Network Provider its working.But with GPS provider only it not working.
change the requestLocationUpdates method so that it updates faster and with less change in coordinates. Change it to:-
requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
Try it now. If possible move the phone some meters so that it is detected soon by the GPS satellites. I am presuming that GPS is switched on.
GPS does not provide a 'get my location on demand' functionality. You have to be patient and wait until the device gets a fix from several satellites. This may take several minutes, even with a clear view of the sky. This is why the OS implements this as a callback. onLocationChanged runs when the device has a fix and you just have to wait for it.
Will you please elaborate more? Do you need to find the current location in mapview by Long or Lat? If this is your question then do one thing :
Find Lat and Long by sending manually through DDMS or by generating Lat and Lang on click at mapview :
It can be done by:
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = " + loc.getLatitude() + "Longitud = " + loc.getLongitude();
Toast.MakeTest(getApplicationContext(),Text,Toast.Length_Long).show()
}
So by this you can get your lat and Long.After getting Lat and Long at mapView's click listener you can write below code:
Projection proj = view1.getProjection();
GeoPoint loc = proj.fromPixels((int)ev.getX(), (int)ev.getY());
//Getting Lat and Log
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
GeoPoint point = new GeoPoint( (int) (loc.getLatitudeE6()),(int) (loc.getLongitudeE6()));
//Getting location from lat and Long
String address="";
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
Toast t =Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude+" name: "+address, Toast.LENGTH_LONG);
t.show();
You will get output as you click at mapview.
For click event on MapView please write above code in dispatchTouchEvent() as
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_UP:
//write above code here
}
}
Try this one.
Edit: Check your code with this given below code.
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location loc) {
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " + "Latitud = "
+ loc.getLatitude() + "Longitud = " + loc.getLongitude();
latituteField.setText(String.valueOf(loc.getLatitude()));
longitudeField.setText(String.valueOf(loc.getLongitude()));
}
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT).show();
}
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "Gps Enabled",Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
First check Your GPS is enabled or disabled.After enabling GPS ,using Location listener to get current location.I am using follwing code to get gps location
String sourceLat, sourceLong;
LocationManager locManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
txtCurrLat = (TextView) findViewById(R.id.txtCurrLat);
txtCurrLong = (TextView) findViewById(R.id.txtCurrLong);
mapView = (MapView) findViewById(R.id.mapview);
geoPoint = null;
mapView.setSatellite(false);
locManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000L,500.0f, locationListener);
Location location = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
double fromLat = location.getLatitude();
double fromLong = roundTwoDecimals(location.getLongitude());
Toast.makeText(getApplicationContext(), fromLat +fromLong+"" , Toast.LENGTH_SHORT).show();
sourceLat = Double.toString(fromLat);
sourceLong = Double.toString(fromLong);
txtCurrLat.setText(sourceLat+","+sourceLong);
btnShow.setOnClickListener(this);
}else{
Toast.makeText(getApplicationContext(), "Location is not avilable", Toast.LENGTH_SHORT).show();
}
}
private void updateWithNewLocation(Location location) {
String latLongString = "";
if (location != null) {
double lat = location.getLatitude();
double lng = location.getLongitude();
sourceLat = Double.toString(lat);
sourceLong = Double.toString(lng);
latLongString = sourceLat + "," + sourceLong;
} else {
latLongString = "No location found";
Toast.makeText(getApplicationContext(), latLongString+"", Toast.LENGTH_SHORT).show();
}
txtCurrLat.setText(latLongString);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Disabled.Please enabale gps", Toast.LENGTH_SHORT ).show();
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
Toast.makeText( getApplicationContext(), "Gps is Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};

Categories

Resources