GPS Locations only from network - android

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

Related

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

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.

How to get GPS location and send in SMS android

I can not get the GPS to work. I am saving it in a SharedPreference called gps and it will print in a Toast as "http://maps.google.com/?q=" + lat + " , " + lon
this is so when it is sent in a SMS they receiver can just push the link and it opens the map. But when the toast comes up it is blank. Below is my code.
private void showLocation() {
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(bestProvider);
LocationListener loc_listener = new LocationListener() {
public void onLocationChanged(Location l) {}
public void onProviderEnabled(String p) {}
public void onProviderDisabled(String p) {}
public void onStatusChanged(String p, int status, Bundle extras) {}
};
locationManager
.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
location = locationManager.getLastKnownLocation(bestProvider);
double lat, lon;
try {
lat = location.getLatitude();
lon = location.getLongitude();
} catch (NullPointerException e) {
lat = -1.0;
lon = -1.0;
}
prefs.setPreferenceString(getApplicationContext(),"gps" ,"http://maps.google.com/?q=" + lat + " , " + lon);
}
to find your location try to use GPSTracker. link
And use this code.
gps = new GPSTracker(LauncherActivity.this);
latitude = gps.getLatitude();
longitude = gps.getLongitude();
And one more things, check your device, is it support GPS? And is it (GPS) enable? If your device's GPS is not enable, you will get null....
For more help... check my github repo
I am trying to make such app, here are the code for toast that works well:
Handler handler3 = new Handler(Looper.getMainLooper());
handler3.post(new Runnable(){
#Override
public void run(){
Toast.makeText(context,"mensagem",Toast.LENGTH_LONG).show();
}
});

Gps android same point after moving

Gps is working fine but when i am idle at one place for about 1 or 2 hours and if i start moving but the gps is taking the previous location where am before 1 hour its not changing.
Question when i am moving without any stops gps is locating correct but if i stop for some time and move... then the location doesn't change.
Please help me out of this.Thanks in advance.
if(isGPSEnabled)
{
try
{
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 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) {}
});
if(locationManager!=null)
{
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);
stopUsingGPS();
}
else
{
logFile log=new logFile();
log.createFile("GPS NULL");
}
}
when you stop some where check the GPS icon in notification bar whether its blinking or steady fixed.
if its blinking that means your GPS signal is lost and trying to get
location from satellite.
if its fixed means you are getting updated location.
condition 1 can be occurred when you are under high-tension voltage line or inside building or you are underground or no satellite in reach.
to boost up your gps search always try to use A-GPS.

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);
}

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