Current user location is not retrieving - android

This is my last question about gps
Getting 0.0 for latitude and longitude while showing current location in map
Now here is the code I'm using to get the user's current location.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(crta, true);
Location loc = null;
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
}
LocationListener mlocListener = new MyLocationListener();
mlocListener.onLocationChanged(loc);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 10, mlocListener);
public class MyLocationListener implements LocationListener{
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location loc) {
if (null != loc) {
String Text = "Your current location is: \n" + "Latitude = \n"
+ loc.getLatitude() + "\nLongitude = \n" + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
GeoPoint myGeoPoint = new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
mpc.animateTo(myGeoPoint);
mpc.setZoom(10);
objMapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText(getApplicationContext(), "gps disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "gps enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Now the problem I'm facing is, it is not showing me the current location when the gps is turned on. The loc object , loc = mlocManager.getLastKnownLocation(provider); always returns null. I got the value for provider as gps.
But if I turn of my gps connection, the same loc object will have relevant information and it works partiall correct. That means, it gives me the nearest location. I mean the full city location where I am sitting.
But if I on my gps connection, it does not give me even the city location also, does not enters if loop only inside location listener class. I am not getting what is going wrong here.
Any one can tell me how to solve it?
Update:
This is the value I get for loc object if my gps is off
Location[mProvider=network,mTime=1331718353322,mLatitude=12.9053401,mLongitude=74.8359128,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy=36.0,mExtras=Bundle[mParcelledData.dataSize=148]].
But if the gps is on, loca return null

CustomLocationManager.Java
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class CustomLocationManager {
private LocationManager mLocationManager;
private LocationValue locationValue;
private Location networkLocation = null;
private Location gpsLocation = null;
private Timer mTimer;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private static CustomLocationManager _instance;
private CustomLocationManager() {}
public static CustomLocationManager getCustomLocationManager() {
if (_instance == null) {
_instance = new CustomLocationManager();
}
return _instance;
}
public LocationManager getLocationManager(Context context) {
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return mLocationManager;
}
public boolean getCurrentLocation(Context context, LocationValue result) {
locationValue = result;
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
try {
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!isGpsEnabled && !isNetworkEnabled)
return false;
if (isGpsEnabled)
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
if (isNetworkEnabled)
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
mTimer = new Timer();
mTimer.schedule(new GetLastKnownLocation(), 20000);
return true;
}
LocationListener gpsLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(networkLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener networkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(gpsLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastKnownLocation extends TimerTask {
CurrentLocationHandler handler;
GetLastKnownLocation() {
handler = new CurrentLocationHandler();
}
#Override
public void run() {
mLocationManager.removeUpdates(gpsLocationListener);
mLocationManager.removeUpdates(networkLocationListener);
if (isGpsEnabled)
gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkEnabled)
networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
handler.sendEmptyMessage(0);
}
}
private class CurrentLocationHandler extends Handler {
#Override
public final void handleMessage(Message msg) {
if (gpsLocation != null && networkLocation != null) {
if (gpsLocation.getTime() > networkLocation.getTime())
locationValue.getCurrentLocation(gpsLocation);
else
locationValue.getCurrentLocation(networkLocation);
return;
}
if (gpsLocation != null) {
locationValue.getCurrentLocation(gpsLocation);
return;
}
if (networkLocation != null) {
locationValue.getCurrentLocation(networkLocation);
return;
}
locationValue.getCurrentLocation(null);
}
}
}
LocationValue.Java
import android.location.Location;
public abstract class LocationValue {
public abstract void getCurrentLocation(Location location);
}
YourActivity.Java
private void getCurrentLocation() {
CustomLocationManager.getCustomLocationManager().getCurrentLocation(this, locationValue);
}
public LocationValue locationValue = new LocationValue() {
#Override
public void getCurrentLocation(Location location) {
// You will get location here if the GPS is enabled
if(location != null) {
Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
}
}
};
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

First of all I'm not familiar with the Android location API, but did you try the GPS outside? Since GPS doesn't work inside buildings, it's pretty hard to retrieve the location of your mobile device using only your GPS. When indoors, typically your "GPS" position is determined using your WiFi acces point connection instead.

Related

Can't Get GPS Current Location's Latitude and Longitude Android

I am trying to get Current Location using either GPS or Network Provider. My device's GPS is enabled but I'm not getting Latitude and Longitude.
GpsTracker.java:
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// if Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}
Service.Java
public class WifiScaningService extends IntentService {
GpsTracker gpsTracker;
double latitude;
double longitude;
public WifiScaningService() {
super("WifiScaningService");
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onCreate() {
Log.e("service call","service call");
}
#Override
protected void onHandleIntent(Intent intent) {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
gpsTracker = new GpsTracker(this);
String stringLatitude = String.valueOf(gpsTracker.latitude);
latitude = Double.parseDouble(stringLatitude);
Log.e("Latitude",stringLatitude);
String stringLongitude = String.valueOf(gpsTracker.longitude);
longitude = Double.parseDouble(stringLongitude);
Log.e("Longitude",stringLongitude);
return START_STICKY;
}
}
I have included necessary permissions in AndroidManifest.xml file. Required to show current location.
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
uses-permission android:name="android.permission.INTERNET"/>
MainActivity:
import android.location.Address;
import android.location.Location;
import com.example.havadurumumenu.MyLocationManager.LocationHandler;
public class MainActivityextends Activity implements LocationHandler{
public MyLocationManager locationManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
currentLocation();
}
});
}
public void currentLocation(){
locationManager = new MyLocationManager();
locationManager.setHandler(this);
boolean isBegin = locationManager.checkProvidersAndStart(getApplicationContext());
if(isBegin){
//if at least one of the location providers are on it comes into this part.
}else{
//if none of the location providers are on it comes into this part.
}
}
#Override
public void locationFound(Location location) {
Log.d("LocationFound", ""+location);
//you can reach your Location here
//double latitude = location.getLatitude();
//double longtitude = location.getLongitude();
locationManager.removeUpdates();
}
#Override
public void locationTimeOut() {
locationManager.removeUpdates();
//you can set a timeout in MyLocationManager class
txt.setText("Unable to locate. Check your phone's location settings");
}
MyLocationManager:
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.annotation.SuppressLint;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
/*---------- Listener class to get coordinates ------------- */
public class MyLocationManager implements LocationListener {
public LocationManager locationManager;
public LocationHandler handler;
private boolean isLocationFound = false;
public MyLocationManager() {}
public LocationHandler getHandler() {
return handler;
}
public void setHandler(LocationHandler handler) {
this.handler = handler;
}
#SuppressLint("HandlerLeak")
public boolean checkProvidersAndStart(Context context){
boolean isBegin = false;
Handler stopHandler = new Handler(){
public void handleMessage(Message msg){
if (!isLocationFound) {
handler.locationTimeOut();
}
}
};
stopHandler.sendMessageDelayed(new Message(), 15000);
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 1000, this);
isBegin = true;
}
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 1000, this);
isBegin = true;
}
return isBegin;
}
public void removeUpdates(){
locationManager.removeUpdates(this);
}
/**
* To get city name from coordinates
* #param location is the Location object
* #return city name
*/
public String findCity(Location location){
/*------- To get city name from coordinates -------- */
String cityName = null;
Geocoder gcd = new Geocoder(AppController.getInstance(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getLocality();
}
catch (IOException e) {
e.printStackTrace();
}
return cityName;
}
#Override
public void onLocationChanged(Location loc) {
isLocationFound = true;
handler.locationFound(loc);
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
public interface LocationHandler{
public void locationFound(Location location);
public void locationTimeOut();
}
}
Also add all the permissions below in your Manifest.xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
I Solved by exchanging position of both methods.
First app trying to get location using GPS if GPS is not enabled then using network provider method.
public class GpsTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS Status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
public double latitude;
public double longitude;
// The minimum distance to change updates in metters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10
// metters
// The minimum time beetwen updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GpsTracker(Context context) {
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
// getting network status
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS Enabled", "GPS Enabled");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if Network Provider Enabled get lat/long using GPS Services
if (isNetworkEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
updateGPSCoordinates();
}
}
}
}
} catch (Exception e) {
// e.printStackTrace();
Log.e("Error : Location",
"Impossible to connect to LocationManager", e);
}
return location;
}
public void updateGPSCoordinates() {
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
}

Unable to get location from GPS?

I am trying to get the location from the GPS but not able to get it. this is because the location is accessed by the Network provider.
If I am commenting all the code of network provider then the GPS location returns null.
I have tried so much, but unable to resolve this.
If anybody can help then it will be great help for me.
I am using this link for the reference..
https://stackoverflow.com/a/3145655/1395259
Here is my code:
MainActivity.java
package com.example.locationsimple;
import com.example.locationsimple.MyLocation.LocationResult;
import android.location.Location;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
TextView textView;
LocationResult locationResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textViewLocation);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
locationResult = new LocationResult(){
#Override
public void gotLocation(Location location) {
while(true)
{
Log.i("Log", "Inside while loop ");
if(location != null)
{
Log.i("Log", "Here the location is not null");
if(location.getLatitude() !=0.0 || location.getLongitude() != 0.0)
{
if(location.getAccuracy() < 100)
{
Log.i("Log", "Inside while loop BREAKS");
try
{
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, ""+loc, Toast.LENGTH_LONG).show();
textView.setText(loc);
}
catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
break;
}
else
{
Log.i("Log", "no Accuracy");
Log.i("Log", "latti"+location.getLatitude()+" Longi "+location.getLongitude()+" Accur "+location.getAccuracy()+location.getProvider());
break;
}
}
}
else
{
Log.i("Log", "Here got the location is null");
break;
}
}
//textView.setText(location.getLatitude()+"::"+location.getLongitude()+"::"+location.getAccuracy()+" Provider "+location.getProvider());
}
};
MyLocation myLocation = new MyLocation();
myLocation.getLocation(MainActivity.this, locationResult);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
MyLocation.java
package com.example.locationsimple;
import java.util.Timer;
import java.util.TimerTask;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
Context mContext;
public boolean getLocation(Context context, LocationResult result)
{
mContext = context;
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
/*Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_HIGH);
lm.getBestProvider(criteria, true);*/
//exceptions will be thrown if provider is not permitted.
try
{
gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch(Exception ex)
{
ex.printStackTrace();
}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled || !network_enabled)
{
showSettingsAlert();
return false;
}
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 30000);
return true;
}
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setCancelable(false);
// Setting Dialog Title
alertDialog.setTitle("GPS Is Not Enabled");
// Setting Dialog Message
alertDialog.setMessage("Please Enabled Wireless Network And GPS");
// On pressing Settings button
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
dialog.cancel();
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
// Showing Alert Message
alertDialog.show();
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
// lm.removeUpdates(locationListenerNetwork);
Location net_loc=null;
Location gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Thanks..
You can use the below service for getting gps.just invoke this service at the begining.
public class MyService extends Service {
LocationManager locationManager;
#Override
public void onCreate() {
//
// TODO Auto-generated method stub
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
/** Criteria for selecting best provider */
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
/** Passing criteria and select only enabled provider */
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
/** calls the Location Listner */
locationManager.requestLocationUpdates(provider, 500, 0,locationListener);
}
private final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void updateWithNewLocation(Location location)
{
System.out.println("+++++++++++++++++++SASI+++++++++++++++++++++++++++++++++++++++++");
String latLongString, addressString = null;
double lat = 0, lng = 0;
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
//latLongString = "Lat:" + lat + "\nLong: " + lng;
/** Getting Address */
} else {
latLongString = "No location found";
addressString = "No location found";
}
//System.out.println("###########" + addressString + lat + lng);
SearchDeals.latPoint=location.getLatitude();
SearchDeals.lngPoint=location.getLongitude();
Deals_route.sourcelati=location.getLatitude();
Deals_route.sourcelong=location.getLongitude();
}
#Override
public void onDestroy() {
super.onDestroy();
//
//Toast.makeText(this, "GPS Service Destroyed", Toast.LENGTH_LONG).show();
locationManager.removeUpdates(locationListener);
System.out.println("########### inside ONDESTROY GPS listener removed");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
//
Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
//Toast.makeText(this, "Service started", Toast.LENGTH_LONG).show();
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
I've just tested the above code on my device and everything is working smoothly, not sure what is the problem at your end.
Important notes:
Please make sure you have the permission to access GPS location in your manifest file
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"/>
The code may not work properly on the emulator , better test on actual device. if you don't have access to one , please checkout the DMMS Emulator Control to generate location data
Edit:
you need to commit out the Location data related to Network Provider.
and Also remove the textView.setText from your LocationResult object because textView is null. so the fixes:
getLocation(Location location) {
.........
String loc = "Lattitude: "+location.getLatitude()+" longi "+location.getLongitude()+" Accur "+location.getAccuracy()+" Time "+location.getTime() +" "+location.getProvider();
Log.i("Log",loc);
Toast.makeText(MainActivity.this, loc, Toast.LENGTH_LONG).show();
}
and comment out the network code from your MyLocation class
// if(network_enabled)
// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);

GPS doesn't search on my Android

I'm new on android programation and I have a problem with my aplication.
My Gps just doesn't search for location, or anything else.
And yes, my GPS is tunned on.
The manifest cointains the permitions:
ACCESS_COARSE_LOCATION and ACCESS_FINE_LOCATION.
Could somebody help me?
public class LocationTest extends Activity implements
LocationListener {
private static final String[] A = { "invalid", "n/a", "fine", "coarse" };
private static final String[] P = { "invalid", "n/a", "low", "medium",
"high" };
private static final String[] S = { "out of service",
"temporarily unavailable", "available" };
private LocationManager mgr;
private TextView output;
private String best;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
output = (TextView) findViewById(R.id.output);
log("Location providers:");
dumpProviders();
Criteria criteria = new Criteria();
best = mgr.getBestProvider(criteria, true);
log("\nBest provider is: " + best);
log("\nLocations (starting with last known):");
if (best != null) {
Location location = mgr.getLastKnownLocation(best);
dumpLocation(location);
}
}
#Override
protected void onResume() {
super.onResume();
// Start updates (doc recommends delay >= 60000 ms)
if (best != null) {
mgr.requestLocationUpdates(best, 15000, 1, this);
}
}
#Override
protected void onPause() {
super.onPause();
// Stop updates to save power while app paused
mgr.removeUpdates(this);
}
public void onLocationChanged(Location location) {
dumpLocation(location);
}
public void onProviderDisabled(String provider) {
log("\nProvider disabled: " + provider);
}
public void onProviderEnabled(String provider) {
log("\nProvider enabled: " + provider);
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
log("\nProvider status changed: " + provider + ", status="
+ S[status] + ", extras=" + extras);
}
/** Write a string to the output window */
private void log(String string) {
output.append(string + "\n");
}
/** Write information from all location providers */
private void dumpProviders() {
List<String> providers = mgr.getAllProviders();
for (String provider : providers) {
dumpProvider(provider);
}
}
/** Write information from a single location provider */
private void dumpProvider(String provider) {
LocationProvider info = mgr.getProvider(provider);
StringBuilder builder = new StringBuilder();
builder.append("LocationProvider[")
.append("name=")
.append(info.getName())
.append(",enabled=")
.append(mgr.isProviderEnabled(provider))
.append(",getAccuracy=")
.append(A[info.getAccuracy() + 1])
.append(",getPowerRequirement=")
.append(P[info.getPowerRequirement() + 1])
.append(",hasMonetaryCost=")
.append(info.hasMonetaryCost())
.append(",requiresCell=")
.append(info.requiresCell())
.append(",requiresNetwork=")
.append(info.requiresNetwork())
.append(",requiresSatellite=")
.append(info.requiresSatellite())
.append(",supportsAltitude=")
.append(info.supportsAltitude())
.append(",supportsBearing=")
.append(info.supportsBearing())
.append(",supportsSpeed=")
.append(info.supportsSpeed())
.append("]");
log(builder.toString());
}
/** Describe the given location, which might be null */
private void dumpLocation(Location location) {
if (location == null)
log("\nLocation[unknown]");
else
log("\n" + location.toString());
}
}
I normally don't do this, but I almost have to go.
This is the code I use, it works. (just put this in a new project).
I didn't clean it, because I ripped it from my other project, but it does work, when you make a new project and just copy/paste this.:
import java.util.Timer;
import java.util.TimerTask;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.widget.Toast;
public class MainActivity extends Activity {
Timer timer1;
LocationManager lm;
boolean gps_loc = false;
boolean gps_enabled=false;
boolean network_enabled=false;
double lat;
double lng;
String gps_location;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getLocation(this, locationResult);
}
public LocationResult locationResult = new LocationResult() {
public void gotLocation(final Location location) {
try {
lat = location.getLatitude();
lng = location.getLongitude();
if (lat != 0.0 && lng != 0.0) {
String sLat;
String sLng;
sLat = Double.toString(lat);
sLng = Double.toString(lng);
gps_location = sLat + " " + sLng;
Toast.makeText(getBaseContext(), "We got gps location!",
Toast.LENGTH_LONG).show();
System.out.println("We got gps");
System.out.println("lat = "+lat);
System.out.println("lng = "+lng);
}
} catch (Exception e) {
}
}
};
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
return false;
}
if(gps_enabled){
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 35000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
Also add this in manifest:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
No time to explain now, maybe tomorrow if you still need it.
It prints the latitude and longitude in your logcat.

android GPS current Location null value

i use the following code for getting the current latitude and longitude in services but it always return null. please help me.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println("provider "+provider);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Try this code for current location:
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10,
10, mlocListener);
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
VisualCV.this);
dlgAlert.setMessage("Gps Disabled ");
dlgAlert.setTitle("Message");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps enabled", Toast.LENGTH_SHORT ).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public void onLocationChanged(Location loc)
{
// TODO Auto-generated method stub
Latitud = loc.getLatitude();
longtitude = loc.getLongitude();
lang = String.format("%.4f", longtitude);//LONGITUDE
lati = String.format("%.4f", Latitud);//LATITUDE
}
}
Use this piece of code may be it may help you
import com.example.ConfigClass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
}
This is my code
First startGpsCallBack, then stop it and then call startGPSCallBackAgain method
Check it and let me know if this solves your problem
Try this.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
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();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
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)
{
}
}

grab the lat and lng

So i found this script to get the best location and have added it to a app. When i call for the location it just gives a random number after the package name (com.android.package.currentactivity$1#randomcode)
MyLocation myLocation = new MyLocation();
private void locationClick() {
myLocation.getLocation(this, locationResult));
}
public LocationResult locationResult = new LocationResult(){
#Override
public void gotLocation(final Location location){
//Got the location!
});
}
};
and the MyLocation.java
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class MyLocation {
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
public boolean getLocation(Context context, LocationResult result)
{
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled)
return false;
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 20000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
lm.removeUpdates(locationListenerGps);
lm.removeUpdates(locationListenerNetwork);
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
}
What im trying to get is the lat and lng so i can use is in my activity.
You will need to be more explicit on where do you get that string, so we can help you pinpoint the issue, but that string represent your Activity instance as a String.
public String toString ()
Since: API Level 1
Returns a string containing a concise, human-readable description of this object. Subclasses are encouraged to override this method and provide an implementation that takes into account the object's type and data. The default implementation is equivalent to the following expression:
getClass().getName() + '#' + Integer.toHexString(hashCode())
See Writing a useful toString method if you intend implementing your own toString method.
Returns a printable representation of this object.
Edit: It's not your activity, but an inner class inside it (this is told by the $1 part). Perhaps the MyLocation instance?
You need to add one or both of these to your manifest.xml:
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" />
This is the bulk of my location code. Use it. It works.:
/**************************************************************************
* helper functions for starting/stopping monitoring of Location changes below
**************************************************************************/
public void startListening() {
if (networkLocationListener == null && gpsLocationListener == null) {
// make new listeners
networkLocationListener = new BegetLocationListener(LocationManager.NETWORK_PROVIDER);
gpsLocationListener = new BegetLocationListener(LocationManager.GPS_PROVIDER);
// request very rapid updates initially. after first update, we'll put them back down to a much lower frequency
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 200, networkLocationListener);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 200, gpsLocationListener);
}
Location networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (networkLocation != null) {
appModel.setLocation(networkLocation);
}
updateDistances(appModel.getLocation());
}
private void stopListening() {
if (networkLocationListener != null)
locationManager.removeUpdates(networkLocationListener);
if (gpsLocationListener != null)
locationManager.removeUpdates(gpsLocationListener);
gpsLocationListener = null;
networkLocationListener = null;
}
private void handleListenerDisabled(BegetLocationListener listener) {
if (!appModel.getFlags().hasLocationMessageBeenDisplayed()) {
if (networkLocationListener.locationStatusKnown && gpsLocationListener.locationStatusKnown) {
if (networkLocationListener.locationIsEnabled && !gpsLocationListener.locationIsEnabled) {
showAlert(YES_NETWORK_NO_GPS_MSG, BaseActivity.DIALOG_LOCATION);
appModel.getFlags().setLocationMessageDisplayed(true);
} else {
showAlert(NO_NETWORK_NO_GPS_MSG, BaseActivity.DIALOG_LOCATION);
appModel.getFlags().setLocationMessageDisplayed(true);
}
}
}
}
private void handleLocationChanged(Location location) {
if (location == null) {
return;
}
if (isBetterLocation(location, appModel.getLocation())) {
appModel.setLocation(location);
stopListening();
}
}
private class BegetLocationListener implements LocationListener {
private String provider = "";
private boolean locationIsEnabled = true;
private boolean locationStatusKnown = true;
public BegetLocationListener(String provider) {
this.provider = provider;
}
#Override
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
handleLocationChanged(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
startListening();
}
public void onProviderDisabled(String provider) {
locationStatusKnown = true;
locationIsEnabled = false;
handleListenerDisabled(this);
}
}
Obviously you'll want to remove the appModel stuff and the custom dialog stuff.

Categories

Resources