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.
}
Related
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.!
I am calling toast message in AndroidGPSTrackingActivity.class. how to fetch geo locations after every 1 minutes.. With below code I am getting only once
public class AndroidGPSTrackingActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
// check if GPS enabled
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText( getApplicationContext(),"Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;"+latitude);
} else {
gps.showSettingsAlert();
}
}
in manifest I given
<service android:name=".GPSTracker" />
Code:
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 = 100 * 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();
}
System.out.println("responsel:::"+latitude);
// return latitude
return latitude;
}
/**
* Function to get longitude
* */
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
// return longitude
System.out.println("responsel:::"+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;
}
}
Try this!
Wrap the toast code in a method and call it recursively using Handler and Runnable:
public class AndroidGPSTrackingActivity extends Activity {
Handler showLocationHandler;
Runnable showLocationRunnable;
private static final int DELAY_TIME = 1000 * 60; //delay time - 1 minute
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
showLocationHandler = new Handler();
showLocationRunnable = new Runnable() {
#Override
public void run() {
showLatLongToast();
}
};
//call the method once
showLatLongToast();
}
public void showLatLongToast() {
if (gps.canGetLocation()) {
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
Toast.makeText(getApplicationContext(), "Your Locion is - \nLat: " + latitude
+ "\nLog: " + longitude, Toast.LENGTH_LONG).show();
System.out.println("respmaillati::;;" + latitude);
} else {
gps.showSettingsAlert();
}
//call the same method after some delay
showLocationHandler.postDelayed(showLocationRunnable, DELAY_TIME);
}
#Override
protected void onDestroy() {
super.onDestroy();
//kill this runnable when ever you want to stop displaying toast like this
showLocationHandler.removeCallbacks(showLocationRunnable);
}
}
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 doing application, we are in inside the room or not. I have to stored 4 corner values means doing polygon. But i cant get exactly value in the same position, it gets different values in the same position. How it get solution this problem??
Code:
MainActivity.java
public class MainActivity extends Activity {
Button btnShowLocation;
TextView tvLat;
TextView tvLang;
TextView tvInsideRoom;
dbHandler myDbHelper;
// GPSTracker class
GPSTracker gps;
Handler mHandler1;
tvInsideRoom = (TextView)findViewById(R.id.insideRoom);
btnShow = (Button) findViewById(R.id.btnShow);
// show location button click event
btnShow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mHandler1 = new Handler();
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while (true) {
try {
Thread.sleep(100);
mHandler1.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
// creating GPS Class object
GPSTracker gps = new GPSTracker (MainActivity.this);
// check if GPS location have some values
if (gps.canGetLocation()) {
double currentlat = gps.getLatitude();
double currentlong = gps.getLongitude();
tvLat = (TextView)findViewById(R.id.lat);
tvLang = (TextView)findViewById(R.id.lang);
tvLat.setText(""+currentlat);
tvLang.setText(""+currentlong);
boolean boolFlag = myDbHelper.isInsideRoom(currentlat,currentlong);
tvInsideRoom.setText("");
if(boolFlag)
tvInsideRoom.setText("You are in inside Room");
else
tvInsideRoom.setText(""+boolFlag);
} else {
// no current location
gps.showSettingsAlert();
}
}
});
} catch (Exception e) {
// TODO: handle exception
}
}
}
}).start();
}
}); }
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;
// 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 = 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) {
Log.d("Accuracy1 := ", ""+location.getAccuracy());
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) {
Log.d("Accuracy2 := ", ""+location.getAccuracy());
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) {
this.location = location;
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}}
The accuracy of location tracking can vary vastly. What you are trying to achieve will never work because of an insufficient accuracy. Especially inside a room, but even with GPS.
Depending on where you are, network cell-towers, wifi or GPS will be used to determine the current location, and all with a different accuracy. Even outside, it usually takes a few seconds until you get a GPS fix.
Use getAccuracy() to check if your location is somewhat useful with the current fix.
I follow a tutorial that clicking on a button it call a class that bring all the GPS lat/long information, the thing is that I need it to be call automatically and each certain time and displacement of the device It had to display new values on the screen but it only show the first time. This is what I have:
public class GPS extends Service implements LocationListener{
private final Context mContext;
//flag for GPS status
boolean isGPSEnable = false;
// Flag for network status
boolean isNetworkEnable = false;
// flag for GPS status
boolean canGetLocation = false;
Location location; //location
double latitude; //latitude
double longitude; //longitude
// the minimum distances to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // Minimun distance 10 meters
// The minimum time between updates in millisenconds
private static final long MIN_TIME_BTW_UPDATES = 1000 * 60 * 1; // 1 MINUTE
// Declaring a Location Manager
protected LocationManager locationManager;
public GPS(Context context){
this.mContext = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(Context.LOCATION_SERVICE);
//getting GPS status
isGPSEnable = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
//getting network status
isNetworkEnable = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnable && !isNetworkEnable){
// no network provider is enable
}
else {
this.canGetLocation = true;
if(isNetworkEnable){
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) 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 Enable get lat/long using GPS Services
if(isGPSEnable){
if(location == null){
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BTW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
Log.d("GPS ENABLE", "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((LocationListener) GPS.this);
}
}
/**
* function to get latitude
*/
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
//return latitude
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
//return longitude
return longitude;
}
/**
* Function to check GPS/wifi enable
* #return boolean
*/
public boolean canGetLocation(){
return this.canGetLocation;
}
/**
* Function to show settings alert dialog
* On pressing Settings button will launch Settings Options
*/
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
// Setting Dialog Title
alertDialog.setTitle(mContext.getString(R.string.AlertDialog_Tittle));
// Setting Dialog Message
alertDialog.setMessage(mContext.getString(R.string.dialog_message));
// On pressing Setting button
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
}
});
// On pressing cancel button
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
}
#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) {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
on the main activity
public class GPSActivity extends ActionBarActivity {
private EditText edTLatitud;
private EditText edTLongitud;
private EditText edTCompass;
private EditText edTDirecc;
private SensorManager sensorManager;
private Sensor compassSensor;
// GPS class
GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gpsactivity);
edTCompass = (EditText)this.findViewById(R.id.edTxtBrujula);
edTDirecc = (EditText)this.findViewById(R.id.edTxtBrujdireccion);
edTLatitud = (EditText)this.findViewById(R.id.edTxtLatitud);
edTLongitud = (EditText)this.findViewById(R.id.edTxtLongitud);
gps = new GPS(GPSActivity.this);
// Check if GPS is enable
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// Print on the screen the coordinates
UpdateGPSonScreen(latitude, longitude);
}
else {
// can't get location
// GPS or network is not enable
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
thanks in advice
You are calling UpdateGPSonScreen only once. If you need constant updates you would call that method everytime within onLocationChanged(Location location) but in order for you to do that you would need to refactor a little.