Getting location on service does not work - android

I am using location service to listen location on background. But I have a problem with getting current location in service. It does not give me the proper result but 0,0 as coordinates. When I do the same operations on main activity, it gives the expected result. I think it is about context given to the gpstracker as a parameter but do not know what to do.
public class LocationService extends Service {
Context context;
Timer timer;
String latitude, longitude;
private String id;
GPSTracker gps;
public LocationService() {
}
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
id = intent.getStringExtra("id");
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
int isHere = isHere();
Log.i("isHere", isHere + "");
updateUserStatus(isHere);
}
}, 0, 200000);
return START_STICKY;
}
private int isHere() {
gps = new GPSTracker(context);
if (!gps.canGetLocation()) {
gps.showSettingsAlert();
}
if (gps.canGetLocation()) {
latitude = gps.getLatitude() + "";
longitude = gps.getLongitude() + "";
if (Math.abs(39.875303 - Double.parseDouble(latitude)) <= 0.001 || Math.abs(32.879980 - Double.parseDouble(longitude)) <= 0.001)
return 1;
else
return 0;
}
return 0;
}
private void updateUserStatus(int isHere) {
Call<Kisi> x = ManagerAll.getInstance().updateLocation(id, isHere);
x.enqueue(new Callback<Kisi>() {
#Override
public void onResponse(Call<Kisi> call, Response<Kisi> response) {
if (response.isSuccessful())
Log.i("durum", "başarılı");
}
#Override
public void onFailure(Call<Kisi> call, Throwable t) {
}
});
}
}
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;
// 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(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.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;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
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;
}
}
Taken here

try with this code.
this code work for me.
package com.yourpackage.tracker;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import com.orhanobut.hawk.Hawk;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import id.glite.transporter.GLiteApplication;
import id.glite.transporter.data.DataManager;
import id.glite.transporter.data.model.post.LocationUpdate;
import id.glite.transporter.util.rx.scheduler.SchedulerUtils;
import io.nlopez.smartlocation.SmartLocation;
import timber.log.Timber;
public class LocationTrackerService extends Service {
// constant
public static final long NOTIFY_INTERVAL = 3 * 60 * 1000; // 3 minutes
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;
private DataManager dataManager;
private Context mContext;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mContext = this;
dataManager = GLiteApplication.get(getBaseContext()).getComponent().dataManager();
// cancel if already existed
if (mTimer != null) {
mTimer.cancel();
} else {
// recreate new
mTimer = new Timer();
}
// schedule task
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask {
#Override
public void run() {
// run on another thread
// display toast
mHandler.post(this::doTrackLocation);
}
private void doTrackLocation() {
if (idTask != null) {
SmartLocation.with(getBaseContext()).location()
.start(location -> {
List<Double> position = new ArrayList<>();
position.add(0, location.getLatitude());
position.add(1, location.getLongitude());
});
}
}
}
}

Make sure you enable the GPS on your phone and allowing the location permission as well.!

Related

Longitude and Latitude showing 0.0 in Service

I want to make a notification that contain longitude and latitude in every 5 minutes. And I make 2 service, but I the longitude and latitude can not be displayed in my apps.
this is my GPS Service
package com.example.michael.eksperimen4gpstrack;
/**
* Created by Michael on 01/12/2015.
*/
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
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.provider.Settings;
import android.util.Log;
import java.util.Timer;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private static final long NOTIFY_INTERVAL = 10 * 1000; // 10 detik
private Timer mTimer = null;
// 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(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.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;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
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;
}
}
And this is my timer service
package com.example.michael.eksperimen4gpstrack;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Handler;
/**
* Created by Michael on 14/12/2015.
*/
public class LocService extends Service
{
public static final long NOTIFY_INTERVAL = 5*1000; // 10 detik
private android.os.Handler mHandler = new android.os.Handler();
public Timer mTimer = null;
GPSTracker gps;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate()
{
if(mTimer != null)
{
mTimer.cancel();
}
else
{
mTimer = new Timer();
}
mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0, NOTIFY_INTERVAL);
}
class TimeDisplayTimerTask extends TimerTask
{
#Override
public void run()
{
gps = new GPSTracker(getApplicationContext());
mHandler.post(new Runnable()
{
#Override
public void run()
{
// 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 + "\n\n"+getDateTime(), 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();
}
}
});
}
}
public int onStartCommand(Intent intent, int flags, int startId)
{
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
public void onDestroy()
{
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}
private String getDateTime()
{
// get date time in custom format
SimpleDateFormat sdf = new SimpleDateFormat("[yyyy/MM/dd - HH:mm:ss]");
return sdf.format(new Date());
}
}
When toast displayed, the longitude and latitude still 0.0, anyone can help me please?
Gratia
Replace your TimeDisplayTimerTask with following code:
Initialize gps within run method.
class TimeDisplayTimerTask extends TimerTask
{
#Override
public void run()
{
mHandler.post(new Runnable()
{
#Override
public void run()
{
gps = new GPSTracker(getApplicationContext());
// 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 + "\n\n"+getDateTime(), 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();
}
}
});
}
}
Wait sometime because getting gps-coordinates from gps takes some time.

Service not executing Location Updates

I have created an IntentService class which i used to send device data to a web service whether the app is running or is terminated. Here's my code:
import android.app.IntentService;
import android.content.Intent;
import android.location.Location;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class PostMyCoordinatesService extends IntentService implements GPSTracker.GPSUpdateListener,WebService.WebServiceListener {
GPSTracker gpsTracker;
DataCacher dataCacher;
WebService webService;
private String TAG = Constants.GLOBAL_TAG+"-PostService";
public static final String SERVICE_NOTIFIER ="<mypackagename>";
public PostMyCoordinatesService(String name) {
super(name);
}
public PostMyCoordinatesService(){
super("PostMyCoordinatesService.");
}
#Override
protected void onHandleIntent(Intent intent) {
Log.v(TAG,"HANDLE INTENT IS CALLED!");
startMyLocationUpdates();
}
private void startMyLocationUpdates() {
//reset location update callbacks if it exists.
if (gpsTracker != null) {
gpsTracker.stopUsingGPS();
}
gpsTracker = null;
dataCacher = DataCacher.getInstance();
if(dataCacher== null)
dataCacher = new DataCacher(getApplicationContext());
String seekbarCachedValue = dataCacher.getStringForKey(Constants.KEY_FREQUENCYUPDATES);
boolean allowGPS = dataCacher.getBooleanForKey(Constants.KEY_ALLOW_DEVICEGPS, false);
if(allowGPS) {
gpsTracker = new GPSTracker(getApplicationContext(), (Integer.parseInt(seekbarCachedValue) + 60));
gpsTracker.setOnGPSUpdateListener(this);
Log.v(TAG,"Starting gps updates.");
}
else{
Log.v(TAG, "Sending gps data was disabled.");
}
}
#Override
public boolean stopService(Intent name) {
super.stopService(name);
if (gpsTracker != null) {
gpsTracker.stopUsingGPS();
Log.v(TAG,"GPS tracking was disabled");
}
return true;
}
#Override
public void onGPSUpdated(Location updatedLocation) {
dataCacher = DataCacher.getInstance();
if (dataCacher == null)
dataCacher = new DataCacher(getApplicationContext());
boolean allowGPS = dataCacher.getBooleanForKey(Constants.KEY_ALLOW_DEVICEGPS, false);
if (allowGPS) {
Log.v(TAG, "Updating my coordinates>.." + updatedLocation.toString());
sendMyLocation(updatedLocation);
}
}
private void sendMyLocation(Location location){
dataCacher = DataCacher.getInstance();
if(dataCacher==null)
dataCacher = new DataCacher(getApplicationContext());
//get phone number
String phoneNumber = dataCacher.getUserPhone();
String url =Constants.URL_POST_DEVICE_LOCATION+
phoneNumber+"/"+
location.getLatitude()+"/"+
location.getLongitude()+"/"+
location.getSpeed()+"/"+
location.getBearing()+"/"+
location.getAltitude();
Log.v(TAG,">>update my coordinates url: "+url);
webService = new WebService(url,this);
webService.execute();
}
#Override
public void didReceiveData(String data, WebService caller) {
Log.v(TAG, "Coordinate Update Service: " + data);
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(SERVICE_NOTIFIER));
}
#Override
public void didReceiveError(String errorMessage) {
Log.v(TAG,"Coordinate Update Service ERROR: "+errorMessage);
}
}
my logcat shows that my handle intent has been called:
08-27 14:03:01.989 26460-26534/? V/Test-PostService﹕ HANDLE INTENT IS CALLED!
08-27 14:03:02.003 26460-26534/? V/Test-PostService﹕ Starting gps updates.
But the callback method onGPSUpdated(Location updatedLocation) wasn't called. I am certain of my GPSTracker class' callbacks for I have used it on my previous projects. What could be the cause of this? What is the more efficient way to send updates to web service for both my app's running and terminated status. I am new to Service by the way. Any help would be greatly appreciated.
EDIT:
Here's my GPSTracker class.
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
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.provider.Settings;
import android.util.Log;
public class GPSTracker extends Service implements LocationListener{
public interface GPSUpdateListener {
void onGPSUpdated(Location updatedLocation);
}
String TAG = Constants.GLOBAL_TAG+"-GPSTracker";
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 = 1; //meters
// The minimum time between updates in milliseconds
private static long MIN_TIME_BW_UPDATES = 1000*60; //default 60 secs
// Declaring a Location Manager
protected LocationManager locationManager;
//snarf added variables
private static GPSTracker trackerInstance;
//snarf added methods
private GPSUpdateListener listener;
public void setOnGPSUpdateListener(GPSUpdateListener updateListener){
listener = updateListener;
}
public static GPSTracker getTrackerInstance(){
return trackerInstance;
}
public GPSTracker(Context context, int updateIntervalSeconds) {
this.mContext = context;
MIN_TIME_BW_UPDATES = updateIntervalSeconds * 1000;
Log.v(TAG,"starting location updates every "+MIN_TIME_BW_UPDATES+ " milliseconds.");
getLocation();
trackerInstance =this;
}
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);
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);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
}
return location;
}
#Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
if(listener!=null)
listener.onGPSUpdated(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;
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
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();
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(GPSTracker.this);
Log.v(TAG,"Stopped gps updates!");
}
}
}

how to run locationlistener in background

I would like to run a locationlistener on my app, that send after every 10m or every 5 seconds an new "Popup". Later I will send my data to the cloud.
This is my GPSTracker class:
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
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.provider.Settings;
import android.util.Log;
import android.widget.Toast;
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;
// 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 * 5 * 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 (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} 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 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;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(GPSTracker.this,"Provider enabled by the user. GPS turned on",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
For my activityclass I have made this:
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
I receive the data, this works. But now I want to run the data in the background so when the location is changed I can implement a function that sends my data to the cloud.
I tried this:
private void startGPSTrackerInBackground() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
String msg = "This message runs in background";
gps = new GPSTracker(MainActivity.this);
if(!gps.canGetLocation()){
gps.showSettingsAlert();
}else{
gps = new GPSTracker(MainActivity.this);
double latitude2 = gps.getLatitude();
double longitude2 = gps.getLongitude();
}
return msg;
}
#Override
protected void onPostExecute(String msg) {
mDisplay.append(msg + "\n");
}
}.execute(null, null, null);
}
But in this function it's not possible to get the information of my GPSTracker class, anyone an idea to make this possible?
Create an independent class, add a GPSTracker member variable and pass it in the constructor. Wrap your task in a method you can invoke later:
public class BackgroundGPSTracker() {
GPSTracker tracker;
public BackgroundGPSTracker(GPSTracker tracker) {
this.tracker = tracker;
}
public void run() {
new AsyncTask<Void,Void,String>() {
#Override
protected String doInBackground(Void... params) {
// Do some background stuff.
}
#Override
protected void onPostExecute(String msg) {
// Do after work stuff
}
}.execute(null, null, null);
}
}
Use:
If you create GPSTracker like this:
gps = new GPSTracker(MainActivity.this);
Then you start the activity passing it to the task:
BackgroundGPSTracker bgGPSTracker= new BackgroundGPSTracker(gps);
bgGPSTracker.run();
EDIT
Use a member variable to store last known location, and timer to schedule updates:
public class CampaignsDiscoverActivity extends Activity{
static final int QUERY_CAMPAINGS_DELAY = 30000;// milliseconds
Location currentLocation;
Timer timer;
void restartTimer() {
timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
sendDataToServerOrWhatever();
}
}, QUERY_CAMPAINGS_DELAY, QUERY_CAMPAINGS_DELAY);
}
void stopTimer() {
if (timer != null) {
timer.cancel();
timer = null;
}
}
void sendDataToServerOrWhatever() {
// Do some stuff using currentLocation
}
Set a listener for locations changes. when location changed is raised, stop the timer, do work and restart it:
void startGPSUpdates() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
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) {
stopTimer();
currentLocation = location;
sendDataToServerOrWhatever();
}
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
// Initialize location.
currentLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (currentLocation == null) {
currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
restartTimer();
}
To start the system just invoke startGPSUpdates.
You should pause listeners when app goes to the background and resume when foreground:
#Override
public void onPause() {
super.onPause();
if (applicationData.isLoggedIn()) {
pauseLocationUpdates();
}
}
#Override
public void onResume() {
super.onResume();
if (applicationData.isLoggedIn()) {
resumeLocationUpdates();
}
}
void pauseLocationUpdates() {
locationManager.removeUpdates(locationListener);
}
void resumeLocationUpdates() {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
}
I think you should do the same with the timer, but the app where I'm using it is not finished and fully tested yet, so you might find bugs.
Hope that helps.

LatLng return 0,0

I am trying to create an app that shows my current location
I have all the permisson neccessary,
I have another class name GPS tracker to get my gps locations
Heres my code :
GPSTracker gpsTracker = new GPSTracker(this);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
map = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
map.setMapType(GoogleMap.MAP_TYPE_NORMAL);
latitude = gpsTracker.latitude;
longitude = gpsTracker.longitude;
LatLng latLng = new LatLng(latitude, longitude);
map.moveCamera(CameraUpdateFactory.newLatLng(latLng));
map.animateCamera(CameraUpdateFactory.zoomTo(18));
Here is the GPSTracker class:
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;
// 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(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.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;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS is settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
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;
}
}
DO NOT USE THE GPS TRACKER CLASS. It's horribly horribly broken. In so many ways I wrote a long blog post about it tonight: see http://gabesechansoftware.com/location-tracking/
Here's the ways its broken:
1)It doesn't track GPS. Sometimes it tracks network location instead
2)The canGetLocation function is broken. It returns true before it has a location
3)Its horribly inefficient, forcing you to poll.
4)It doesn't differentiate stale from fresh data- and doesn't let you do it either
I'd go on but I already wrote it up tonight.
I wrote a much better GPS tracker library at my blog. Here it is repeated for SO use
LocationTracker.java
package com.gabesechan.android.reusable.location;
import android.location.Location;
public interface LocationTracker {
public interface LocationUpdateListener{
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime);
}
public void start();
public void start(LocationUpdateListener update);
public void stop();
public boolean hasLocation();
public boolean hasPossiblyStaleLocation();
public Location getLocation();
public Location getPossiblyStaleLocation();
}
ProviderLocationTracker.java
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class ProviderLocationTracker implements LocationListener, LocationTracker {
// The minimum distance to change Updates in meters
private static final long MIN_UPDATE_DISTANCE = 10;
// The minimum time between updates in milliseconds
private static final long MIN_UPDATE_TIME = 1000 * 60;
private LocationManager lm;
public enum ProviderType{
NETWORK,
GPS
};
private String provider;
private Location lastLocation;
private long lastTime;
private boolean isRunning;
private LocationUpdateListener listener;
public ProviderLocationTracker(Context context, ProviderType type) {
lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
if(type == ProviderType.NETWORK){
provider = LocationManager.NETWORK_PROVIDER;
}
else{
provider = LocationManager.GPS_PROVIDER;
}
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//The provider is on, so start getting updates. Update current location
isRunning = true;
lm.requestLocationUpdates(provider, MIN_UPDATE_TIME, MIN_UPDATE_DISTANCE, this);
lastLocation = null;
lastTime = 0;
return;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
lm.removeUpdates(this);
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
if(lastLocation == null){
return false;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return false; //stale
}
return true;
}
public boolean hasPossiblyStaleLocation(){
if(lastLocation != null){
return true;
}
return lm.getLastKnownLocation(provider)!= null;
}
public Location getLocation(){
if(lastLocation == null){
return null;
}
if(System.currentTimeMillis() - lastTime > 5 * MIN_UPDATE_TIME){
return null; //stale
}
return lastLocation;
}
public Location getPossiblyStaleLocation(){
if(lastLocation != null){
return lastLocation;
}
return lm.getLastKnownLocation(provider);
}
public void onLocationChanged(Location newLoc) {
long now = System.currentTimeMillis();
if(listener != null){
listener.onUpdate(lastLocation, lastTime, newLoc, now);
}
lastLocation = newLoc;
lastTime = now;
}
public void onProviderDisabled(String arg0) {
}
public void onProviderEnabled(String arg0) {
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
}
FallbackLocationTracker.java
package com.gabesechan.android.reusable.location;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
public class FallbackLocationTracker implements LocationTracker, LocationTracker.LocationUpdateListener {
private boolean isRunning;
private ProviderLocationTracker gps;
private ProviderLocationTracker net;
private LocationUpdateListener listener;
Location lastLoc;
long lastTime;
public FallbackLocationTracker(Context context, ProviderLocationTracker.ProviderType type) {
gps = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.GPS);
net = new ProviderLocationTracker(context, ProviderLocationTracker.ProviderType.NETWORK);
}
public void start(){
if(isRunning){
//Already running, do nothing
return;
}
//Start both
gps.start(this);
net.start(this);
isRunning = true;
}
public void start(LocationUpdateListener update) {
start();
listener = update;
}
public void stop(){
if(isRunning){
gps.stop();
net.stop();
isRunning = false;
listener = null;
}
}
public boolean hasLocation(){
//If either has a location, use it
return gps.hasLocation() || net.hasLocation();
}
public boolean hasPossiblyStaleLocation(){
//If either has a location, use it
return gps.hasPossiblyStaleLocation() || net.hasPossiblyStaleLocation();
}
public Location getLocation(){
Location ret = gps.getLocation();
if(ret == null){
ret = net.getLocation();
}
return ret;
}
public Location getPossiblyStaleLocation(){
Location ret = gps.getPossiblyStaleLocation();
if(ret == null){
ret = net.getPossiblyStaleLocation();
}
return ret;
}
public void onUpdate(Location oldLoc, long oldTime, Location newLoc, long newTime) {
boolean update = false;
//We should update only if there is no last location, the provider is the same, or the provider is more accurate, or the old location is stale
if(lastLoc == null){
update = true;
}
else if(lastLoc != null && lastLoc.getProvider().equals(newLoc.getProvider())){
update = true;
}
else if(newLoc.getProvider().equals(LocationManager.GPS_PROVIDER)){
update = true;
}
else if (newTime - lastTime > 5 * 60 * 1000){
update = true;
}
if(update){
lastLoc = newLoc;
lastTime = newTime;
if(listener != null){
listener.onUpdate(lastLoc, lastTime, newLoc, newTime);
}
}
}
}
The interface defines a generic location tracker so you can switch between them. ProviderLocationTracker will allow you to track via GPS or network, depending on the parameter you pass to its constructor. FallbackLocationTracker will track via both, giving you only the most accurate info currently available but falling back to network if GPS isn't ready.
use this code
and implemets your activity from "implements LocationListener"
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000, // 3 sec
5, this);
boolean isGPS = locationManager.isProviderEnabled (LocationManager.GPS_PROVIDER);
if(!isGPS)
{
showSettingsAlert();
GPS_imageview.setBackgroundResource(R.drawable.gpsnonfix);
//Toast.makeText(getApplicationContext(), "Please Start GPS to get more Accurate location", Toast.LENGTH_SHORT) .show();
}
and use following also
#Override
public void onLocationChanged(Location location) {
int a=location.getExtras().getInt("satellites") ;
if(a>4)
{
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
// Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
Double lat=location.getLatitude();
Double lan=location.getLongitude();
}else{
}
String str = "Latitude: "+location.getLatitude()+" \nLongitude: "+location.getLongitude();
Toast.makeText(getBaseContext(), str, Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
/******** Called when User off Gps *********/
Latitude="0.0";
Longitude="0.0";
Toast.makeText(getBaseContext(), "Gps turned off ", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
/******** Called when User on Gps *********/
Toast.makeText(getBaseContext(), "Gps turned on ", Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
This code get no of sattelite .if no of sattelite is greter than 4 then get proper result..thats accuracy of result is good...
When you start your app, your GPS probably has not yet made connection and gives you a default location such as 0,0. If your phone finds its coordinates at a later point in time, your app has no way of detecting this.
This line:
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
states that every time your phone discovers a change of location, the "OnLocationChanged"-method (of the object in which you called that line of code), is called. As far as I can see, you did not implement this method yet.
I suggest the following. Change your third line to:
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, gpsTracker);
So it uses the implementation of the onLocationChanged method of your gpsTracker.
Now, implement the OnLocationChanged-method of the GPSTracker-class which you already defined, but not yet implemented:
#Override
public void onLocationChanged(Location location) {
//This method is triggered every time your location changes.
//The 'location' argument can be used to access the current location.
}

Android GPS won't start after pause

I'm developing an Android app and having some trouble with the implementation of GPS. I've classed my GPS functionality as outlined in this article. Here is the relevant code:
Main Activity:
public class MainActivity extends Activity {
/*
* declare
*/
private Chronometer chrono;
private GPSTracker gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
* hook up interface elements to declared objects
*/
chrono = (Chronometer)findViewById(R.id.chrono);
textState = (TextView)findViewById(R.id.textState);
gps = new GPSTracker(MainActivity.this); // set up gps tracker
//test gps connection and prompt to enable if disabled
if (!gps.canGetLocation()) {
gps.showSettingsAlert();
}
}
#Override
protected void onPause() {
gps.stopUsingGPS();
super.onPause();
}
#Override
protected void onResume() {
gps.getLocation();
if (!gps.canGetLocation()) {
gps.showSettingsAlert();
}
super.onResume();
}
}
And here is my class, called GPSTracker:
/*
* code from
* http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/
*/
package com.example.bustimer;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
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.provider.Settings;
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;
// flag for GPS status
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
private static final String LOG_TAG = "GPS Tracker";
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 5; // 5 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 10 * 1; // 10 seconds
// 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 (!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;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will lauch Settings Options
* */
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle("GPS Settings");
// Setting Dialog Message
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
// On pressing Settings button
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);
}
});
// on pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
// Showing Alert Message
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;
}
}
Previously, the GPS would start when the app was started and turn off anytime I navigated away from the app to do something else. The problem was that the GPS would not start again when I navigated back to the app.
Now, I can't even get the GPS to start when I start the app, and I don't believe I made any changes to the code so I'm completely lost. Any tips?
#
Override
protected void onResume() {
GPSTracker gps;
gps = new GPSTracker(MainActivity.this);
if (gps.canGetLocation()) {
lat = gps.getLatitude();
lon = gps.getLongitude();
} else {
gps.showSettingsAlert();
}
super.onResume();
}

Categories

Resources