Can't Get GPS Current Location's Latitude and Longitude Android - 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;
}
}

Related

Why isn't gps location working on samsung mobile?

I have done a program to fetch users gps location-its working fine in some mobiles but not working in Samsung S4(i9505).
I am running a service and extended LocationListener. Below is the code:
public class MainService extends Service implements LocationListener
{
public double latitude;
public double longitude;
LocationManager mlocManager=null;
LocationListener mlocListener;
Timer timer;
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
mlocListener = this;
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
if (mlocManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
final String provider = LocationManager.GPS_PROVIDER;
// start new timer thread
TimerTask task = new TimerTask()
{
#Override
public void run()
{
Location timerLoc = mlocManager.getLastKnownLocation(provider);
getFrndLocCloudAndSaveInDB();
SimpleDateFormat formata = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
String currentDateandTime = formata.format(new Date());
if(latitude>0 & longitude>0)
{locObj = new LocModel(myName, String.valueOf(latitude), String.valueOf(longitude), currentDateandTime);
Log.d("ccrc","my Loc:::"+ String.valueOf(timerLoc.getLatitude()) + " --|-- " + String.valueOf(timerLoc.getLongitude()) + "at" + currentDateandTime);}
i=i+1;
Log.d("ccrc","from timer--"+ i);
}
};
timer = new Timer(true);
timer.scheduleAtFixedRate(task, 5000, 10000);
}
else {
}
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLocationChanged(Location loc)
{
this.latitude=loc.getLatitude();
this.longitude=loc.getLongitude();
Log.i("latusrvc", String.valueOf(latitude));
}
}
In Log-for ccrc tag i get the result in other mobiles but not showing the longitude and latitude in Samsung S4. Plus GPS is on- i have also checked that. What can be the problem really?
I'm using this class to get latitude and longitude of the current location using GPS with method canGetLocation(). If GPS isn't on we can ask to activate the GPS of the phone by showing a Dailog with method showSettingsAlert.
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 2; // 10 meters
private static final long MIN_TIME_BW_UPDATES = 1000 * 5 * 1; // 1 minute
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
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) {
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
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();
}
return location;
}
/**
* Stop using GPS listener Calling this function will stop using GPS in your
* app
* */
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
*
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Function to show settings alert dialog On pressing Settings button will
* lauch Settings Options
* */
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog
.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#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;
}
}

My Latitude and Longitude are not changing values when I move locations

I am trying to show my latitude and longitude as I move around, but it stays at one value and does not change. Can someone tell me what is wrong with my code? I have already updated the manifest file as well so I'm not sure why it's not working properly. I make calls to it in a writeToFile method in my main activity.
package com.explorer.extractor;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
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; //location
double latitude; //latitude
double longitude; //longitude
//The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; //10 meters
//The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 0; //0 minute
//Declare 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 (!isGPSEnabled && !isNetworkEnabled) {
//no network provider is enabled
} else {
this.canGetLocation = true;
//First get location from network provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.i("Network", "Network");
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
Log.i("NETWORK", "NUMBER 1");
if (location != null) {
Log.i("NETWORK", "is this not null");
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.i("NETWORK", "THE LATITUDE IS " + latitude);
}
}
}
//if GPS Enabled get lat/long usig GPS services
else if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
#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) {
}
public IBinder onBind(Intent arg0) {
return null;
}
//Function to get Latitude
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
//Function to get longitude
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
Log.i("long", "the long is " + longitude);
}
Log.i("long", "the long isnt working");
return longitude;
}
/**
* Function to check if best network provider
*
* #return boolean
*/
public boolean canGetLocation() {
return this.canGetLocation;
}
/**
* Stop Using GPS Listener
* Calling this function stops using GPS in app
*/
public void stopUsingGPS() {
if (locationManager != null) {
locationManager.removeUpdates(GPSTracker.this);
}
}
}
You should be using onLocationChanged() to update the Lat Longs. With that empty, I'm not sure how often you are actually updating your UI

Android location is always null with both NETWORK_PROVIDER and GPS_PROVIDER

This the Service class that I'm trying to use from my MainActivity.java. Running on emulator.
package com.example.sonia.project;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener {
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// 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() {
}
public Location getLocation(Context mContext) {
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 (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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();
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public void onLocationChanged(Location location) {
Log.d("Location", "Location changed!");
this.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;
}
}
This is my onStart() method of MainActivity
#Override
protected void onStart() {
super.onStart();
gps = new GPSTracker();
gps.getLocation(this);
}
And then I call getLocation() again on a button click in MainActity
gps.getLocation(this);
The accepted answer on this question suggests getting location updates and using multiple providers - My current location always returns null. How can I fix this?. I'm doing both.
getLocation() always returns a null location, even if I try to get the location after several minutes. What can do to make it return a valid location and not null?
To get Location in emulator you have to configure through emulator control
For more information refer following link
http://wptrafficanalyzer.in/blog/android-gps-with-locationmanager-to-get-current-location-example/

Getting GPS in service in android

My problem is not new, but none of answers in Stackoverflow was helpful for me.
Situation: I have a service which works with an Alarm. it repeats every 1 minutes and run a service for me. in that service I need to send GPS data to a web server.
the codes are as below:
import android.app.Service;
import android.content.Intent;
import android.location.Location;
import android.os.AsyncTask;
import android.os.IBinder;
import bliksund.taxitracking.tools.Cachepref;
import bliksund.taxitracking.tools.PostData;
public class SendData extends Service {
Cachepref cachepref;
GET_GPS gps;
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
cachepref = new Cachepref(this);
gps = new GET_GPS(this);
new getloc().execute();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private class getloc extends AsyncTask<Void, Void, Void> {
String username;
Double lt;
Double lg;
Location location;
#Override
protected Void doInBackground(Void... params) {
username = cachepref.getUsername();
location = gps.getLocation();
lt = location.getLatitude();
lg = location.getLongitude();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
PostData postData = new PostData(username, 1, lt, lg);
super.onPostExecute(aVoid);
}
}
}
this is my service.
+ PostData will Post the parameters to a web page.
+ Cachepref saves username for user Session.
Problem: When the codes go to get GPS Location. it will make an error that says:
location = gps.getLocation(); // will cause to below line error
Can't create handler inside thread that has not called Looper.prepare()
I used AsynTask to solve this problem, but it is still there.
GET_GPS code are as below:
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
public class GET_GPS extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
protected LocationManager locationManager;
public GET_GPS(Context mContext) {
this.mContext = mContext;
}
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 (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GET_GPS.this);
}
}
/**
* Function to get latitude
* */
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
return longitude;
}
/**
* Function to check GPS/wifi enabled
* #return boolean
* */
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
with the help of ρяσѕρєя K . he said to move these codes to PostExecute and it was running, the problem with PostData happened. and I I solved in the way below. I hope it helps others.
private class getloc extends AsyncTask<Void, Void, Void> {
String username;
Double lt;
Double lg;
Location location;
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
username = cachepref.getUsername();
location = gps.getLocation();
lt = location.getLatitude();
lg = location.getLongitude();
new Thread(new Runnable() {
#Override
public void run() {
PostData postData = new PostData(username, 1, lt, lg);
}
}).start();
super.onPostExecute(aVoid);
}
}

GPS location changing in Android application

I've followed this tutorial for GPS tracking in Android application with this class:
GPSTracker.java
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 (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
// First get location from Network Provider
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("Network", "Network");
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// 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();
}
return location;
}
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
#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;
}
and this is the Activity using the previous class:
AndroidGPSTrackingActivity.java
package com.example.gpstracking;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class AndroidGPSTrackingActivity extends Activity {
Button btnShowLocation;
// GPSTracker class
GPSTracker gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
}else{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
}
How can I receive new position updates from the AndroidGPSTrackingActivity.java ?
How can I get latitude and longitude in AndroidGPSTrackingActivity taken by onLocationChanged that is in GPSTracker class ?
many thanks
I can't write comments yet, so I try here:
I would create a Handler in your Activity and assign it to the the GPSTracker Class:
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// new GPS Informations
// get it by gps.getLatitude() for example
};
};
gps = new GPSTracker(AndroidGPSTrackingActivity.this, handler);
In your GPSTracker Class you have to change the constructor of course:
Handler mHandler;
public GPSTracker(Context context, Handler handler){
...
this.mHandler = handler;
}
And then, just send the info, that the location has changed to your activity:
#Override
public void onLocationChanged(Location location) {
latitude = location.getLatitude();
longitude = location.getLongitude();
mHandler.sendEmptyMessage(0);
}

Categories

Resources