Can't Get Location using LocationManager in Background Service - android

I have created an application that stores your location in database at periodic time in Background service but, it doesn't get location. my code is...
public class LocationService extends Service {
private Double myLat, myLong;
private Location location;
private LocationManager locManager;
private LocationListener locationListener;
private boolean NETWORK_ENABLED, GPS_ENABLED, PASSIVE_ENABLED;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
myLat = 0.00;
myLong = 0.00;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LocationService.this.location = location;
LocationService.this.myLat = location.getLatitude();
LocationService.this.myLong = location.getLongitude();
Toast.makeText(getApplicationContext(), "onLocationChanged", Toast.LENGTH_LONG).show();
insertToDatabase();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {}
};
getMyCurrentLocation();
}
private void getMyCurrentLocation() {
location = null;
locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
NETWORK_ENABLED = false; GPS_ENABLED = false; PASSIVE_ENABLED = false;
NETWORK_ENABLED = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (NETWORK_ENABLED) {
Toast.makeText(getApplicationContext(), "Network Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 45 * 1000l, 1f, locationListener);
}
if (location == null) {
//setGPSOn();
GPS_ENABLED = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(GPS_ENABLED) {
Toast.makeText(getApplicationContext(), "GPS Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0l, 1f, locationListener);
}
//setGPSOff();
}
if (location == null) {
PASSIVE_ENABLED = locManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER);
if(PASSIVE_ENABLED) {
Toast.makeText(getApplicationContext(), "Passive Provider", Toast.LENGTH_LONG).show();
locManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0l, 1f, locationListener);
}
}
try {
location = locManager.getLastKnownLocation(locManager.getBestProvider(new Criteria(), true));
} catch(NullPointerException e) {}
if (location != null) {
myLat = location.getLatitude();
myLong = location.getLongitude();
insertToDatabase();
} else {
Location loc = null;
try {
loc = getLastKnownLocation(this);
} catch(NullPointerException e) {}
if (loc != null) {
myLat = loc.getLatitude();
myLong = loc.getLongitude();
insertToDatabase();
}
}
locManager.removeUpdates(locationListener);
}
private Location getLastKnownLocation(Context context) {
Location location = null;
LocationManager locationmanager = (LocationManager)context.getSystemService("location");
List<?> list = locationmanager.getAllProviders();
boolean i = false;
Iterator<?> iterator = list.iterator();
do {
if(!iterator.hasNext())
break;
String s = (String)iterator.next();
if(i != false && !locationmanager.isProviderEnabled(s))
continue;
Location location1 = locationmanager.getLastKnownLocation(s);
if(location1 == null)
continue;
else {
float f = location.getAccuracy();
float f1 = location1.getAccuracy();
if(f >= f1) {
long l = location1.getTime();
long l1 = location.getTime();
if(l - l1 <= 600000L)
continue;
}
}
location = location1;
i = locationmanager.isProviderEnabled(s);
} while (true);
return location;
}
}
this doesn't give me any location.... and my app is also doesn't Crash or gives any Exception.
I have properly register all permissions in Manifest file...
ACCESS_COARSE_LOCATION
ACCESS_FINE_LOCATION
I can't find what to do?
any help will be appreciated
thanks in advance for Help...

I think your problem is that you remove the listener right away:
locManager.removeUpdates(locationListener); // comment this one out
in getMyCurrentLocation();
You should try to remove your listener in some other places.

Related

onlocationchanged is not called (delay parameter does not apply)

in
locationManager.requestLocationUpdates(provider, time, distance, locationListener);
I knew that without the priority of time and distance, If it satisfied with either condition is called a onLocationChanged()
But onLocationChanged() is not called, only called this circumstances.
1. Load the page and turns on the gps.
2. location listener catch (0,0) white gps is turned on. (onLocationChanged called)
3. gps is turn on finish.
4. The location listener is called after the time that was 'time' parameter of requestLocationUpdates(). (onLocationChanged called)
5. After... onLocationChanged is not called never..
 
1. If the beginning location is normal value, not (0,0). onLocationChanged is not ever call. (Even after the time specified in the parameters)
Why does not apply to the time parameters of requestLocationUpdates()?
this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
Location location;
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 *60;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS Start");
//stopUsingGPS();
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS Finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
Log.d("GPS", "lovationManager remove");
}
}
public void startCallback(){
Log.d("GPS", "startCallback()");
if(isGpsMode != isGPSOn()){
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(!GPSRegistration()){
if(isNetworkOn()){
NetworkRegistration();
}
}
}
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
saveLocation();
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon : " + String.valueOf(lon));
}
public void saveLocation(){
location = null;
if (locationManager != null) {
location = getLastKnownLocation();
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
}
}
private Location getLastKnownLocation() {
List<String> providers = locationManager.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = locationManager.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
bestLocation = l;
}
}
return bestLocation;
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon: "+lon);
if(!(isAvailableLocation(lat, lon))){
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}else{
if(isGPSOn()){
GPSRegistration();
if(isAvailableLocation(lat, lon)){
isGpsMode = !isGpsMode;
}
}
}
}
if(isAvailableLocation(lat, lon)){
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
The reason I coding like this, it must be in Cordova Activity. (And the boss want it... )
+) I delete comment deliberately, because comment was Korean.. (I'm Korean)
I'm sorry that hard to understand because no comment... :(
All, thanks :)
I think you should use Service instead of BroadcastReceiver for GPS.
Self answer.
1. onlocationchanged is not called
This situation is shown when used GPS provider indoors.
When using the GPS provider at room onLocationChange () is not called. (The network provider is operating very successfully.)
So, the value of the gps provider is invalid, must be connected to the network provider.
2. The Time parameters of requestLocationUpdates() is not apply
Although not accurate, I think this is probably related to the length of time.
Because, I confirmed to be the working when by the 5 minutes(1000 * 60 * 5 ms).
It operates abnormally if shorter than the certain period.
I think Certain period is one minutes(1000 * 6 ms).
If you need, this is my code.
private BroadcastReceiver gpsReceiver = new BroadcastReceiver() {
private final String GET_GPS = "getGPS";
private final String SET_GPS = "setGPS";
private final String START_GPS = "startGPS";
private final String FINISH_GPS = "finishGPS";
LocationManager locationManager;
double lat;
double lon;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 5;
boolean isGpsMode = false;
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getStringExtra("action");
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
JSONObject obj = new JSONObject();
if(action.equals(GET_GPS)){
if(isGPSOn()){
try {
obj.put("result","gpsOn");
} catch (JSONException e) {
e.printStackTrace();
}
} else{
try {
obj.put("result","gpsOff");
} catch (JSONException e) {
e.printStackTrace();
}
}
}else if(action.equals(SET_GPS)){
Intent settingIntent= new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
settingIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(settingIntent);
}else if(action.equals(START_GPS)){
Log.d("GPS", "GPS start");
startCallback();
}else if(action.equals(FINISH_GPS)){
Log.d("GPS", "GPS finish");
stopUsingGPS();
}
if(!(obj.toString().equals("{}"))){
sendScript("javascript:getGPS" + "(" + obj + ")");
}
}
public boolean isGPSOn(){
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
public boolean isNetworkOn(){
return locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public void stopUsingGPS(){
Log.d("GPS", "stopUsingGPS()");
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startCallback(){
if(isGPSOn()){
GPSRegistration();
} else if(isNetworkOn()){
NetworkRegistration();
}
}
public boolean GPSRegistration(){
Log.d("GPS", "call location value from GPS");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = true;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
return isAvailableLocation(lat, lon);
}
public void NetworkRegistration(){
Log.d("GPS", "call location value from Network");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListener);
isGpsMode = false;
Log.d("GPS", "lat: " + String.valueOf(lat)+" / lon: " + String.valueOf(lon));
}
public boolean isAvailableLocation(double lat, double lon){
if(lon>124 && lon<132 && lat>33 && lat<43){
return true;
}
return false;
}
private LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lon = location.getLongitude();
}
Log.d("GPS", "onLocationChanged - lat: "+lat+" / lon : "+lon);
if (isAvailableLocation(lat, lon)) {
JSONObject obj = new JSONObject();
try{
obj.put("lat", lat);
obj.put("lon", lon);
}catch( JSONException e){
Log.d("GPS", "onRegistered: JSON exception");
}
sendScript("javascript:sendGPS("+obj+");");
} else {
stopUsingGPS();
if(isGpsMode){
if(isNetworkOn()){
NetworkRegistration();
}
}else{
if(isGPSOn()){
GPSRegistration();
}
}
return;
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onProviderDisabled(String provider) {}
};
};
And I've coded this code in onCreate(),
registerReceiver(gpsReceiver, new IntentFilter("actionName"));
this code in onDestroy().
unregisterReceiver(gpsReceiver);
Then, available through
startIntent(actionName).

how to find location through gps on my phone

I actually wrote the below code on the onclick method of a button,but it is giving null pointer exception,plzz help
public void submit(View v)
{
LocationManager locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location= locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
double mesg1=location.getLatitude();
double mesg2=location.getLongitude();
}
http://developer.android.com/reference/android/location/LocationManager.html
You should register a listener for location updates - see requestLocationUpdates() method.
Also add ACCESS_FINE_LOCATION permission to your Manifest.
hey follows few steps to get proper and accurate current location.
This way provided you current location both by interent as well as gps.
Step 1.
Put this class in your code.
GetCurLocation.java
public class GetCurLocation implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
public static LocationClient mLocationClient;
LocationRequest mLocationRequest;
public static LocationManager locationmanager;
float accuracy = 500;
Activity context;
boolean getLocRegularly = false;
int interval = 1000;
float Radius;
GoogleMap gmap;
SetOnLocationFoundListner OLF;
public interface SetOnLocationFoundListner {
public void onLocationFound(Location location, boolean getLocRegularly,
GoogleMap gmap);
}
public void RemoveUpdates() {
try {
if (mLocationClient != null)
mLocationClient.removeLocationUpdates(this);
if (locationmanager != null)
locationmanager.removeUpdates(LocUpByLocMgr);
} catch (Exception e) {
e.printStackTrace();
}
}
/*
* radius should be in meters
*/
public GetCurLocation(Activity activity, int interval,
boolean getLocRegularly, GoogleMap gmap,
SetOnLocationFoundListner OLF, float Radius) {
this.OLF = OLF;
this.gmap = gmap;
this.context = activity;
this.getLocRegularly = getLocRegularly;
this.interval = interval;
this.Radius = Radius;
if (servicesConnected()) {
mLocationClient = new LocationClient(context, this, this);
mLocationClient.connect();
mLocationRequest = LocationRequest.create();
mLocationRequest.setInterval(interval);
mLocationRequest
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setFastestInterval(interval);
}
locationmanager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
Criteria cr = new Criteria();
String provider = locationmanager.getBestProvider(cr, true);
locationmanager.requestLocationUpdates(provider, interval, 0,
LocUpByLocMgr);
}
private boolean servicesConnected() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(context);
if (ConnectionResult.SUCCESS == resultCode) {
return true;
} else {
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
(Activity) context, 0);
if (dialog != null) {
}
return false;
}
}
#Override
public void onConnectionFailed(ConnectionResult result) {
}
#Override
public void onConnected(Bundle connectionHint) {
try {
Location location = mLocationClient.getLastLocation();
Log.e("testing",
location.getLatitude() + "," + location.getLongitude()
+ "," + location.getAccuracy());
if (location.getAccuracy() < Radius) {
OLF.onLocationFound(location, getLocRegularly, gmap);
locationmanager.removeUpdates(LocUpByLocMgr);
} else
mLocationClient.requestLocationUpdates(mLocationRequest, this);
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected() {
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LC", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LC", location.getAccuracy() + " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient.removeLocationUpdates(this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
android.location.LocationListener LocUpByLocMgr = new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
try {
if (location.getAccuracy() > Radius) {
Log.e("testing LM", location.getAccuracy()
+ " Its Not Accurate");
} else {
Log.e("testing LM", location.getAccuracy()
+ " Its Accurate");
try {
OLF.onLocationFound(location, getLocRegularly, gmap);
if (!getLocRegularly) {
mLocationClient
.removeLocationUpdates(GetCurLocation.this);
locationmanager.removeUpdates(LocUpByLocMgr);
}
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
Step 2.
implement setonlocationfoundlistener in class where you want current location,
and declear one more method in your oncreate and after you will get one location found method and it return location and you can get location.getlatitude and location.getlongitude.
GetCurLocation gcl = new GetCurLocation(activity, 0, true, null, this,
2000);
Step 3. make permission
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
thats all. thanks
public void loc1(View v)
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
Toast.makeText(getApplicationContext(), "latitude",Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "longitude",Toast.LENGTH_LONG).show();
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
String longitude = String.valueOf(location.getLongitude());
String latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
String longitude = "0.00";
String latitude = "0.00";
}
}
}
}

Sample GPS tracker with asynctask : error "provider doesn't exisit: null"

Im looking for a very sample example show longitude and latitude trackers with asynctask.
I find this code https://stackoverflow.com/a/6788457 but he doesn't work :/ i catch this strangely exception "provider doesn't exisit: null" in :
public boolean startService() {
try {
// this.locatorService= new
// Intent(FastMainActivity.this,LocatorService.class);
// startService(this.locatorService);
FetchCordinates fetchCordinates = new FetchCordinates();
fetchCordinates.execute();
return true;
} catch (Exception error) {
Log.i("exception", error.getMessage());
return false;
}
}
After search, I see this post (https://stackoverflow.com/a/13851305/2137454) who explain I must may be use this line :
List<String> providers = locationManager.getAllProviders();
But I don't understand where and how use this tips in my gpstracker class... Someone can help me ?
Here the complete gpstracker class :
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location = null;
double latitude = 0;
double longitude = 0;
double altitude = 0;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000* 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context.getApplicationContext();
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
Log.i("Je tombe...","...ici !");
} else {
this.canGetLocation = true;
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();
altitude = location.getAltitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
Log.i("STOPUSINGGPS", "EFFECTIF");
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude() {
if (location != null) {
Log.i("LATITUDE", "EFFECTIF");
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
Log.i("LONGITUDE", "EFFECTIF");
longitude = location.getLongitude();
}
return longitude;
}
public double getAltitude() {
if (location != null) {
Log.i("ALTITUDE", "EFFECTIF");
altitude = location.getAltitude();
}
return altitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
edit : my gps is turned ON

Why current location of android phone don't change when i change location?

I get location of android phone as:
android.location.Location locationA;
LocationManager locationManager;
Criteria cri = new Criteria();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String tower = locationManager.getBestProvider(cri, false);
locationA = locationManager.getLastKnownLocation(tower);
if (locationA != null) {
// lat = (double) (locationA.getLatitude() * 1E6);
// longi = (double) (locationA.getLongitude() * 1E6);
double lat = locationA.getLatitude();
double longi = locationA.getLongitude();
TextView txt = (TextView) findViewById(R.id.textView1);
String td = String.valueOf(lat) + "," + String.valueOf(longi);
txt.setText(td);
}
Why current location of android phone don't change when i change location and get again current location?
check the time of your location using locationA.getTime(). if it was not up to date wait for a new location and then stop.
private static Location currentLocation;
private static Location prevLocation;
public void yourMethod()
{
locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
MIN_DISTANCE, locationListener);
}
private static LocationListener locationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
gotLocation(location);
}
};
private static void gotLocation(Location location) {
prevLocation = currentLocation == null ?
null : new Location(currentLocation);
currentLocation = location;
if (isLocationNew()) {
// do something
locationManager.removeUpdates(locationListener);
}
}
private static boolean isLocationNew() {
if (currentLocation == null) {
return false;
} else if (prevLocation == null) {
return false;
} else if (currentLocation.getTime() == prevLocation.getTime()) {
return false;
} else {
return true;
}
}

How to get longitude and latitude by GPS in Android?

I can get longitude and latitude by network provider, but unable to get it by GPS. How can I do that?
public void onCreate(Bundle savedInstanceState) {
...
mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (mLocation != null) {
gp1 = getGeoByLocation(mLocation);
gp2 = gp1;
refreshMapView();
if( !mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 2000,
10, mLocationListener);
}else{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000,
10, mLocationListener);
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
Get lat long using GPS in every 10 min.
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}

Categories

Resources