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);
}
}
Related
I've been working on trying to get the current location in android since several days but I didn't find a solution yet.
I know there are similar topics regarding this but in my case the code it didn't work. Is there anyone who has already solved this issue and can help me?
I add some tests I did.
Here's the GPS Tracker class.
package utility;
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
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; // 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) {
try {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
} catch (SecurityException e) {
}
Log.d("Network", "Network");
if (locationManager != null) {
try {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} catch (SecurityException e) {
}
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
// if GPS Enabled get lat/long using GPS Services
if (isGPSEnabled) {
if (location == null) {
try {
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 (SecurityException s) {
}
}
}
}
} 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) {
try {
locationManager.removeUpdates(GPSTracker.this);
} catch (SecurityException e) {
}
}
}
/**
* 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 active. Do you want to open?");
// 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 I instantiated this class in my activity, as follows:
import android.os.Bundle;
import android.app.Activity;
import android.widget.ImageButton;
import android.widget.TextView;
import utility.GPSTracker;
public class AroundMeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_around_me);
TextView location_text = (TextView) findViewById(R.id.location_text);
GPSTracker gps;
double latitude = 0.0;
double longitude = 0.0;
gps = new GPSTracker(AroundMeActivity.this);
// check if GPS enabled
if(gps.canGetLocation())
{
latitude = gps.getLatitude();
longitude = gps.getLongitude();
}
else
{
gps.showSettingsAlert();
}
location_text.setText(latitude + " " + longitude);
}
}
The results is 0.0 for both latitude and longitude.
Thank you in advance guys!!!
Use android LocationMannager
Checkout androidhive tutorial about Android GPS, Location Manager to get started
Here is a great library, very easy to use and lightweight: https://github.com/mrmans0n/smart-location-lib
Just compile it with gradle and thats' it.
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!");
}
}
}
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
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.
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;
}
}