hi there can anybody give me a sample code for get location for every five minutes please i have tried and i can get location once by cliking on button,
but i need it to be displayed once for five minutes.
thank you
this is my code :
public void checkLocation(View v) {
//initialize location manager
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//check if GPS is enabled
//if not, notify user with a toast
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "GPS is disabled.", Toast.LENGTH_SHORT).show();
} else {
//get a location provider from location manager
//empty criteria searches through all providers and returns the best one
String providerName = manager.getBestProvider(new Criteria(), true);
Location location = manager.getLastKnownLocation(providerName);
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Last known location not found. Waiting for updated location...");
}
//sign up to be notified of location updates every 15 seconds - for production code this should be at least a minute
manager.requestLocationUpdates(providerName, 15000, 1, this);
}
}
#Override
public void onLocationChanged(Location location) {
TextView tv = (TextView)findViewById(R.id.locationResults);
if (location != null) {
tv.setText(location.getLatitude() + " latitude, " + location.getLongitude() + " longitude");
} else {
tv.setText("Problem getting location");
}
}
#Override
public void onProviderDisabled(String arg0) {}
#Override
public void onProviderEnabled(String arg0) {}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {}
// Find the closest Bart Station
public String findClosestBart(Location loc) {
double lat = loc.getLatitude();
double lon = loc.getLongitude();
double curStatLat = 0;
double curStatLon = 0;
double shortestDistSoFar = Double.POSITIVE_INFINITY;
double curDist;
String curStat = null;
String closestStat = null;
//sort through all the stations
// write some sort of for loop using the API.
curDist = Math.sqrt( ((lat - curStatLat) * (lat - curStatLat)) +
((lon - curStatLon) * (lon - curStatLon)) );
if (curDist < shortestDistSoFar) {
closestStat = curStat;
}
return closestStat;
}
Here is the code for getting location and set the listener for gps to get current location on few minute and distance, also I have used runnable object to get the location on every few minutes.
Location gpslocation = null;
private static final int GPS_TIME_INTERVAL = 60000; // get gps location every 1 min
private static final int GPS_DISTANCE= 1000; // set the distance value in meter
/*
for frequently getting current position then above object value set to 0 for both you will get continues location but it drown the battery
*/
private void obtainLocation(){
if(locMan==null)
locMan = (LocationManager) getSystemService(LOCATION_SERVICE);
if(locMan.isProviderEnabled(LocationManager.GPS_PROVIDER)){
gpslocation = locMan.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(isLocationListener){
locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER,
GPS_TIME_INTERVAL, GPS_DISTANCE, GPSListener);
}
}
}
}
Now use this method to get the current location and the listener was called on location change with every 1 min and 1000 meter of distance.
For getting every 5 min you can use this handler and runnable to get this location on well set period time:
private static final int HANDLER_DELAY = 1000*60*5;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
myLocation = obtainLocation();
handler.postDelayed(this, HANDLER_DELAY);
}
}, START_HANDLER_DELAY);
Here is GPS listener for location change event:
private LocationListener GPSListener = new LocationListener(){
public void onLocationChanged(Location location) {
// update location
locMan.removeUpdates(GPSListener); // remove this listener
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
You can set interval time for listener and handler same for getting GPS location.
Hi Use the below timer code.
You can use the below options
option 1
this will get the locations if mobile moved 100meters.
captureFrequencey=3*60*1000;
LocationMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, captureFrequencey, 100, this);
have a look at this link http://developer.android.com/reference/android/location/LocationManager.html#requestLocationUpdates%28java.lang.String,%20long,%20float,%20android.location.LocationListener%29
Option 2
TimerTask refresher;
// Initialization code in onCreate or similar:
timer = new Timer();
refresher = new TimerTask() {
public void run() {
handler.sendEmptyMessage(0);
};
};
// first event immediately, following after 1 seconds each
timer.scheduleAtFixedRate(refresher, 0,1000);
//=======================================================
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case REFRESH:
//your code here
break;
default:
break;
}
}
};
Timer will call the handler for your time duration (change 1000 into your required time ).
Hope this will help you.
I used runnable for doing this,
final Runnable r = new Runnable() {
public void run() {
//Here add your code location listener call
handler.postDelayed(this, 300000 );
}
};
handler.postDelayed(r, 300000 );
try like this:
private Handler handler = new Handler();
handler.postDelayed(runnable, 300000);
private Runnable runnable = new Runnable() {
public void run() {
if (location != null) {
onLocationChanged(location);
} else {
System.out.println("Location not avilable");
}
handler.postDelayed(this, 300000);
}
};
Related
when i am trying to get current location using GPS Tracker ,it is tacking time only for first time but i want to get location after specific interval ? i am getting all address line by line like locality sub locality and all but after that interval for first time any solution will be appreciated..
Start your app service in background to get timely location updates.
public class MYService extends Service implements LocationListener {
}
and do async task on timely to get periodic location updates.
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
timer.schedule(doAsynchronousTask, 20000,20000); // 20 sec timer
it will give location updates on every 20 SEC.
Try this code.
make an interface GetLocation
public interface GetLocation {
public void onLocationChanged(Location location);
public void onStatusChanged(String s, int i, Bundle bundle);
public void onProviderEnabled(String s);
public void onProviderDisabled(String s);
}
then make a class CurrentLocation and implements LocationListener
public class CurrentLocation implements LocationListener {
Context context;
LocationManager locationManager;
String provider;
GetLocation getLocation;
public CurrentLocation(Context context) {
this.context = context;
getLocation = (GetLocation) context;
location();
}
public void location() {
// Getting LocationManager object
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// anruag getting last location
// Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals(" ")) {
// Get the location from the given provider
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null)
onLocationChanged(location);
else {
}
// Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// Log.e("Location", location.getProvider() + "==" + location.getAccuracy() + "==" + location.getAltitude() + "==" + location.getLatitude() + "==" + location.getLongitude());
getLocation.onLocationChanged(location);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
ConstantValues.UPlat = String.valueOf(location.getLatitude());
ConstantValues.UPlng = String.valueOf(location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.e("onStatusChanged", "==" + s);
getLocation.onStatusChanged(s, i, bundle);
}
#Override
public void onProviderEnabled(String s) {
Log.e("onProviderEnabled", "==" + s);
getLocation.onProviderEnabled(s);
}
#Override
public void onProviderDisabled(String s) {
Log.e("onProviderDisabled", "==" + s);
getLocation.onProviderDisabled(s);
// alertbox("GPS STATUS", "Your GPS is: OFF");
// Toast.makeText(context, "Please turn on the GPS to get current location.", Toast.LENGTH_SHORT).show();
try {
ConstantValues.showDialogOK("Please turn on the GPS to get current location.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
dialogInterface.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialogInterface.dismiss();
break;
}
}
}, context);
} catch (Exception e) {
Log.e("exception", e.toString()+"==");
}
}
}
call this class in any Activity where you want to get the current location
CurrentLocation currentLocation;
declare these two global variables for minimum distance change and time interval
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
// Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000;
make its object in onCreate
currentLocation = new CurrentLocation(this);
make a method
public void locationWithPermission() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkAndRequestPermissions()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new CurrentLocation(this));
}
}
and call this method in your Activity on any event you want to get Location
What am i trying to do is to get the GPS location from 2 providers, the first one is the GPS which is the most accurate, the second one is the aGPS which is a combination of GPS and network. I am doing that because aGPS can get location even in tall buildings when normal gps takes more time to get.
What i want is to try getting location from the first provider(GPS) for 10 seconds, if in those 10 seconds i get a location!=null, i break the timed loop and take the result to the main thread, which is the main activity. ELSE ill take the location from the second provider(aGPS) if available. If none of the provider where able to get a location, i will return null after the 10 seconds.
The problem i am facing is, when i do a timed loop, the app freezes for 10 seconds so im not able to get the location to the main activity.
Here i am trying to get the location on the HomeActivity class that extends Activity:
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new GPSTracker(HomeActivity.this);
location=locationtracker.getLocation();
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
This is the GPSTracker Class where the 2 providers try to get location:
public class GPSTracker{
Context con;
LocationManager locMgr;
private double longgps;
private double latgps;
private double longnetwork;
private double latnetwork;
private LocationListener gpsLocationListener;
private LocationListener networkLocationListener;
public GPSTracker(final Context context){
con = context;
locMgr = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationProvider high = locMgr.getProvider(locMgr.getBestProvider(
createFineCriteria(), true));
LocationProvider low = locMgr.getProvider(locMgr.getBestProvider(
createCoarseCriteria(), true));
//GET LOCATION FROM GPS
gpsLocationListener = new LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
alertDialogBuilder
.setMessage(
"Please Enable GPS and Network For Accurate Result")
.setCancelable(false)
.setPositiveButton("Enable GPS",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent callGPSSettingIntent = new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(callGPSSettingIntent);
}
});
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertDialogBuilder.create();
alert.show();
}
#Override
public void onLocationChanged(Location location) {
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
//GET LOCATION FROM GPS + NETWORK
networkLocationListener=new LocationListener() {
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
}
public static Criteria createFineCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_FINE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public static Criteria createCoarseCriteria() {
Criteria c = new Criteria();
c.setAccuracy(Criteria.ACCURACY_COARSE);
c.setAltitudeRequired(false);
c.setBearingRequired(false);
c.setSpeedRequired(false);
c.setCostAllowed(true);
c.setPowerRequirement(Criteria.POWER_HIGH);
return c;
}
public double[] getLocation() {
double location[] = new double[2];
Calendar cal = Calendar.getInstance();
Long endtime = cal.getTimeInMillis() + 10000;
while (Calendar.getInstance().getTimeInMillis() < endtime) {
if (longgps != 0 && latgps != 0) {
location[0] = longgps;
location[1] = latgps;
Log.i("LocationGetter", "GPS: Longitude:" + location[0]
+ " Latitude:" + location[1]);
break;
} else if (longnetwork != 0 && latnetwork != 0) {
location[0] = longnetwork;
location[1] = latnetwork;
Log.i("LocationGetter", "Network: Longitude:" + location[0]
+ " Latitude:" + location[1]);
}
}
locMgr.removeUpdates(networkLocationListener);
locMgr.removeUpdates(gpsLocationListener);
networkLocationListener = null;
gpsLocationListener = null;
return location;
}
}
Isn't this just a multithreading problem. Instead of doing the work on the main thread, one could create a second thread so that it doesn't matter if that thread is idle for 10 seconds.
Incidentally, instead of relying on any single provider, I think it's better to use all providers and trust them according to their accuracy using a Kalman filter. See my answer here for a simple Kalman filter that seems to work in the context of Android location providers.
Make your GPSTracker class abstract by declaring the method updatedLocation(Location loc) without body. In code
public abstract class GPSTracker{
.......
private Location mLocation;
public void updateLocation(Location loc);
private CountDownTimer mNetworkCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
// this onFinish() will be called if not cancel by Gps
locMgr.removeUpdates(networkLocationListener);
updateLocation(mLocation);
}
};
private CountDownTimer mGpsCountDown = new CountDownTimer(10000, 10000)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
locMgr.removeUpdates(gpsLocationListener);
}
};
.........
gpsLocationListener = new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// Get a gps fix cancel both countdowns and listeners
mGpsCountDown.cancel();
mNetworkCountDown.cancel();
locMgr.removeUpdates(gpsLocationListener);
locMgr.removeUpdates(networkLocationListener);
// The calling class will get the fix
updateLocation(location);
longgps = location.getLongitude();
latgps = location.getLatitude();
//Log.i("LocationGetter", "GPS: Longitude:" + longgps+ " Latitude:" + latgps);
}
};
locMgr.requestLocationUpdates(high.getName(), 0, 0f,gpsLocationListener);
mGpsCountDown.start();
.......
networkLocationListener=new LocationListener() {
..........
#Override
public void onLocationChanged(Location location) {
// No cancelation here, Gps will cancel if it gets a fix
mLocation = location;
longnetwork = location.getLongitude();
latnetwork = location.getLatitude();
//Log.i("LocationGetter", "Network: Longitude:"+ longnetwork + " Latitude:" + latnetwork);
}
};
locMgr.requestLocationUpdates(low.getName(), 0, 0f,networkLocationListener);
mNetworkCountDown.start();
.........
// remove the getLocation()
}
In HomeActivity class create a class that extends GPSTracker
public class HomeActivity extends Activity {
.........
public class MyGPSTracker extends GPSTracker
{
public void updateLocation(Location location)
{
// location would be null if both Gps and Network did not
// get a fix in 10 seconds
if (location != null)
{
// do whatever you want with this location fix
// If you want to know if this fix is from GPS or Network
// just use String provider = location.getProvider()
Log.i("LocationGetter","Result: Longitude:"+location.getLongitude()+" Latitude:"+location.getLatitude);
}
}
}
Button btnRedCross = (Button) this.findViewById(R.id.btnRedCross);
btnRedCross.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
OutRequestsDatabaseHandler db =new OutRequestsDatabaseHandler();
OutRequest outreq = new OutRequest();
outreq.setName("Red Cross");
//TODO get the message from LocalUser db
Calendar cal = Calendar.getInstance();
outreq.setDate(cal.getTimeInMillis());
outreq.setMessage("My Message");
outreq.setType("RedCross");
//outreq.setLongitude(12.123456);
//outreq.setLatitude(12.123456);
db.addOutRequest(HomeActivity.this, outreq);
//HERE I AM TRYING TO GET THE LOCATION
GPSTracker locationtracker=new MyGPSTracker(HomeActivity.this);
// You will get the location when updateLocation is called by the
// MyGPSTracker class
Log.i("LocationGetter","Result: Longitude:"+location[0]+" Latitude:"+location[1]);
}
});
}
This question already has answers here:
What is the simplest and most robust way to get the user's current location on Android?
(28 answers)
Closed 9 years ago.
What is the best way to get the current location in android for the following scenario,
If GPS is not available, get location from Network provider
If GPS is available and can get current location, get location from GPS provider
If GPS is available but can't get current location(i.e continuously searching location), get location from the network provider.
now i can getting a location from network if gps not available, the best answer to satisfy the above scenario is highly appreciated. thanks in advance.
Well, you can use Timer and TimerTask classes.
LocationManager manager;
TimerTask mTimertask;
GPSLocationListener mGPSLocationListener;
int i = 0; //Here i works as counter;
private static final int MAX_ATTEMPTS = 250;
public void getCurrentLocation() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mGPSLocationListener = new GPSLocationListener();
manager.addGpsStatusListener(mGPSStatusListener);
mTimerTask = new LocTimerTask(LocationManager.GPS_PROVIDER);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
} else {
turnGPSOn();
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,
50.0f, mGPSLocationListener);
}
if(manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L,
50.0f, mNetworkLocationListener);
}
if (manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.v(TAG, "GPS ENABLED");
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000L, 50.0f, mGPSLocationListener);
}
myLocTimer = new Timer("LocationRunner", true);
myLocTimer.schedule(mTimerTask, 0, 500);
}
GPSStatusListener
private GpsStatus.Listener mGPSStatusListener = new GpsStatus.Listener() {
#Override
public synchronized void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.v(TAG, "GPS SAtellitestatus");
GpsStatus status = manager.getGpsStatus(null);
mSattelites = 0;
Iterable<GpsSatellite> list = status.getSatellites();
for (GpsSatellite satellite : list) {
if (satellite.usedInFix()) {
mSattelites++;
}
}
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
/*
* Toast.makeText(getApplicationContext(), "Got First Fix",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STARTED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Started",
* Toast.LENGTH_LONG).show();
*/
break;
case GpsStatus.GPS_EVENT_STOPPED:
/*
* Toast.makeText(getApplicationContext(), "GPS Event Stopped",
* Toast.LENGTH_LONG).show();
*/
break;
default:
break;
}
}
};
LocationListener
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location argLocation) {
location = argLocation;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
TimerTask class
class LocTimerTask extends TimerTask {
String provider;
public LocTimerTask(String provider) {
this.provider = provider;
}
final Handler mHandler = new Handler(Looper.getMainLooper());
Runnable r = new Runnable() {
#Override
public void run() {
i++;
Log.v(TAG, "Timer Task run" + i);
location = manager.getLastKnownLocation(provider);
if (location != null) {
Log.v(TAG, "in timer task run in if location not null");
isGPS = true;
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
} else {
Log.v(TAG, "in timer task run in else location null");
isGPS = false;
if (location == null && i == MAX_ATTEMPTS) {
Log.v(TAG, "if 1 max attempts done");
turnGPSOff();
location = manager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Log.v(TAG,
"if 1 max attempts done Location from network not null");
Log.v(TAG,
"if 1 max attempts done Location from network not null coordinates not null");
onLocationReceived(location);
myLocTimer.cancel();
myLocTimer.purge();
mTimerTask.cancel();
return;
}
} else {
return;
}
}
i = 0;
}
};
public void run() {
mHandler.post(r);
}
}
Here the timer has been scheduled to run on every 500 milliseconds. Means, on every 500 milliseconds the timer task's run method will executed. In run method try get location from GPS provider for specific no. of attempts(Here MAX_ATTEMPTS) say 5 or 10. If it gets location within specified no. of attempts then use that location else if counter(Here i) value has exceeded MAX_ATTEMPTS, then get location from Network Provider. on getting location, I had passed that location to callback method onLocationReceived(Location mLoc) in which you can do your further work with location data. Here's how you will use callback method:
Listener
public interface OnLocationReceivedListener {
public void onLocationReceived(Location mLoc); //callback method which will be defined in your class.
}
Your class should implement the above defined listener. In your class:
#Override
public void onLocationReceived(Location mLoc) {
//Do your stuff
}
Hope it helps. If anybody have a better approach, then please let me know.
If GPS is available and can get current location,
For the above question you can try like this..
Using this you can get the latitude and longitude for the current location then pass the value to get the map.
public class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = “My current location is: “ +
“Latitud = “ + loc.getLatitude() +
“Longitud = “ + loc.getLongitude();
Toast.makeText( getApplicationContext(),
Text,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Disabled”,
Toast.LENGTH_SHORT ).show();
}
#Override
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
“Gps Enabled”,
Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
}
class member boolean mIsGpsFix;
Request Gps location update and set up a countdown timer
mCountDown.start();
private CountDownTimer mCountDown = new CountDownTimer(time to wait for Gps fix, same as right)
{
#Override
public void onTick(long millisUntilFinished)
{
}
#Override
public void onFinish()
{
// No fix after the desire amount of time collapse
if (!mIsGpsFix)
// Register for Network
}
};
When my map activity is called I make a call in the onCreate to addUserMapPoint. This function contains two instances where I try to get the location information using myOverlay.getMyLocation. On the initial load of this activity the result of the first attempt returns a null GeoPoint and after the main UI thread completes the second attempt located in the listener thread of myOverlay.runOnFirstFix(new Runnable()… is call after a second and does contain a GeoPoint that does contain a lat and lon. The call inside this listener function does appear to put the dot on the map and the line mapController.animateTo(gp) does move the map to my location. My app has a refresh button that when clicked fires off this activity again. I need the lat and lon in order to fetch location data from another service. After the refresh, the second time through the map activity code I was expecting the first call to myOverlay.getMyLocation() would now be able to get the GeoPoint, but it is still null.
If I’m not able to get the GeoPoint by this first call to myOverlay.getMyLocation then how can I pass the lat and lon value from the second call found in the myOverlay.runOnFirstFix(new Runnable()… thread. You will notice that I have been trying to add the lat and lon to MyApp which is helper bean class but the lat and lon in this class is null even after the refresh. If I manually set a lat and lon manually in the addUserMapPoint function the first time the activity is accessed these values are retained. I’m guessing that this is because it is being set on the main UI thread.
public class MapActivity extends com.google.android.maps.MapActivity {
private MapView mapView = null;
private MapController mapController = null;
private MyLocationOverlay myOverlay = null;
public static MyApp app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
app = (MyApp) getApplicationContext();
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
List<Overlay> mapOverlays = mapView.getOverlays();
mapOverlays.clear();
addUserMapPoint(mapView);
if (!app.isLocServOff()) {
//map other points – service call to get items from our service near lat and lon
addOtherMapPoints(mapOverlays);
} else {
Toast.makeText(app.getApplicationContext(),"Current location could not be found.",Toast.LENGTH_LONG).show();
}
}
private void addUserMapPoint(MapView mapView){
myOverlay = new MyLocationOverlay(app.getApplicationContext(), mapView);
myOverlay.disableCompass();
myOverlay.enableMyLocation();
if(app.getMyLat()==null||app.getMyLon()==null){
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
}else{
app.setLocServOff(true);
}
}
myOverlay.runOnFirstFix(new Runnable() {
public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
}
});
mapView.getOverlays().add(myOverlay);
}
}
Your help is being requested for the following question.
How can I get a GeoPoint that contains a lat and lon in the main UI thread or how can I pass these values from GeoPoint I am able to get from the myOverlay.runOnFirstFix(new Runnable()… thread?
If you are going to suggest that I use Handler or runOnUiThread please provide code example that passes the lat and lon back to something that can be used by the main UI thread/map view. I have tried things like the following code that did not produce the desired outcome. I was able to get the toast message to show up, but was not able to get the lat and lon passed in a way I could use.
final Handler handler = new Handler();
myOverlay.runOnFirstFix(new Runnable() {
#Override public void run() {
handler.post(new Runnable() {
#Override public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
//Toast.makeText(getApplicationContext(),"wowoowowowoowoowowow",Toast.LENGTH_LONG).show();
}
});
}
});
I've also used code like the following to get the lat and lon and it works, but because the current location would sometimes be a different lat and lon than whas was being returned becuase for example I could not get a gps signal but yet an old value was returned. I added checks to see if the lat/lon data was older than 2 minutes, but I still could not match up the most recent lat and lon with that that is returned by myOverlay.getMyLocation.
LocationManager locMgr = (LocationManager)appcontext.getSystemService(Context.LOCATION_SERVICE);
MyLocationListener locLstnr = new MyLocationListener();
//fetch current location for current location
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locLstnr, appcontext.getMainLooper());
Bellow you can find some examples on how to get the current location in the UI thread, but first of all, some background information.
GPS may take some time (15 seconds to 1 minute) to get the first fix after the request for new location is made. This is the reason you your first attempt to get it from myOverlay fails, and only after the first fix you can get the value.
During this blackout period you can use getLastKnownLocation() to get the last good known GPS location if you are in a hurry. If not availble it returns null
The code:
Last Known Location
LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
Location loc = locMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(loc != null){
//we have a valid location. Check location date
}
Requesting a Single Location Update
LocationManager locMgr=(LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
locMgr.requestSingleUpdate(LocationManager.GPS_PROVIDER, locationListener, appcontext.getMainLooper);
Requesting a Continuous Location Update
LocationManager locMgr = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
//use 0 for minDistance and minDistance between updates if you need the maximum update frequency.
locMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minDistance, minTime, locationListener);
Location Listener for Single and Continuous position update
This is the last piece of code, and is the place where you get the new fresh locations requested above.
When a new location that match your request critirea defined above is retrieved by GPS, this listener is immediately called, unless you device is busy doing something else that can't be interrupted (i.e. callback is on a paused thread or that hit a lock).
From within the onLocationChanged() you can set any class level filed as appropriate. If you registered the listener from the UI thread, then this will be running running on the UI.
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location fix) {
fix.setTime(fix.getTime() + timeZoneOffset); //Add Timezone offset if needed
//here you have a fresh new location in fix...
//You can set the value of any class level field from here
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
Regards.
handler.post(new Runnable() {
#Override public void run() {
GeoPoint gp = myOverlay.getMyLocation();
if(gp!=null){
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
app.setLocServOff(false);
// HERE WE HAVE VALID gp VALUE AND WE NEED TO SHARE IT
mapController.animateTo(gp);
}else{
app.setLocServOff(true);
}
}
});
I think that your app.set/get|MyLat/Lon not working because you call them from different threads. To fix it synchronize set and get methods for MyLat/Long. (create Object for synchronization and sync on it)
Or if you like your way with handler this should work:
final Handler handler = new Handler(); // BE SURE TO RUN THIS LINE ON UI THREAD
...
myOverlay.runOnFirstFix(new Runnable() {
#Override public void run() {
// THIS PART WORKS AS BEFORE
final GeoPoint gp = myOverlay.getMyLocation();
mapController.animateTo(gp);
...
// AND THIS RUNNABLE TO UPDATE MyLat/MyLong FROM UI THREAD
handler.post(new Runnable() {
#Override public void run() {
app.setMyLat(Helper.latLon1E6Calc(gp.getLatitudeE6()));
app.setMyLon(Helper.latLon1E6Calc(gp.getLongitudeE6()));
});
}
});
Some of the most important points you must take into account while seeking Device's location are:
Satellite GPS fix is not guaranteed to be received in adequate amount of time. E.g. the device is inside a building / not under open sky.
Make sure the satellite GPS listeners are not kept active for long. Keeping the listener ON will imply keeping the GPS radio on all the time making it the biggest battery drain reason.
In the below code example, the poll method in LinkedBlockingQueue doesn't return until either a specified time interval is over or a Location is queued in.
Use something like the below to get the current Location:
Location getCurrentLocation() {
long startmillis = 0;
LinkedBlockingQueue<Location> mQueue = new LinkedBlockingQueue<Location>();
try{
long millisSinceLastCollection = System.currentTimeMillis() - startmillis;
startmillis = System.currentTimeMillis();
mQueue.clear();
// Register for Satellite GPS listener as well as Network GPS listener.
registerGPSListeners();
// Wait for a maximum of one minutes for a fix
Location firstfix = mQueue.poll(1, TimeUnit.MINUTES);
if(firstfix != null && firstfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
return firstfix;
}
long elapsedmillis = System.currentTimeMillis() - startmillis;
long remainingmillis = ONE_MINUTE_IN_MS - elapsedmillis;
if (remainingmillis <= 0){
return firstfix;
}
Location secondfix = mQueue.poll(remainingmillis, TimeUnit.MILLISECONDS);
if(secondfix != null && secondfix.getProvider().equals(LocationManager.GPS_PROVIDER)) {
return secondfix;
}
/*
* In case we receive fix only from Network provider, return it.
*/
if(firstfix != null && firstfix.getProvider().equals(LocationManager.NETWORK_PROVIDER)) {
return firstfix;
}
} catch(Exception e){
Logger.e("GPS: Exception while listening for the current location", e);
} finally {
Logger.i("GPS: Unsubscribing from any existing GPS listeners");
unregisterGPSListeners();
}
}
// GPS issue fix edit.
private void registerGPSListeners() {
LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
if(locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER))
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 30000, 100, oneShotNetworkGPSLocationListener, MyAppApp.getAppContext().getMainLooper());
if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 100, oneShotSatelliteGPSLocationListener, AirWatchApp.getAppContext().getMainLooper());
}
}
private void unregisterGPSListeners(){
final LocationManager locationManager = (LocationManager)MyApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(oneShotSatelliteGPSLocationListener);
locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
}
//One shot location listener
protected LocationListener oneShotSatelliteGPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
mQueue.put(location);
} catch (InterruptedException e) {
Logger.e("Exception in putting new Location to the queue", e);
}
Logger.d("GPS: Location received from Satellite GPS Provider");
unregisterGPSListeners();
}
public void onProviderDisabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
};
//One shot location listener
protected LocationListener oneShotNetworkGPSLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
try {
mQueue.put(location);
} catch (InterruptedException e) {
Logger.e("Exception in putting new Location to the queue", e);
}
Logger.d("GPS: Location received from Network GPS Provider");
// Stop Listener for one-shot location fix from Network GPS provider.
final LocationManager locationManager = (LocationManager)AirWatchApp.getAppContext().getSystemService(Context.LOCATION_SERVICE);
locationManager.removeUpdates(oneShotNetworkGPSLocationListener);
Logger.d("GPS: Unsubscribed the network location listener.");
}
public void onProviderDisabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
};
Android modifies the user interface and handles input events from one single user interface thread(main thread).
If the programmer does not use any concurrency constructs, all code of an Android application runs in this thread.
GPS is the best way to determine a user's location, but pinging a global positioning satellite too much will quickly drain a mobile device's battery, take long time to get user location and this method doesn't always work indoors. You are not getting your location in first attempt that's why you are getting null over there.
Android's Network Location Provider figures out a user's location based on cell tower and Wi-Fi signals. It not only uses less battery power than GPS, but it's also faster and it works whether the user is outside or inside.
I am giving my Working Code below that show progress dialog, listen for user's location & after getting location show user's location overlay on Google-map
I assume that you have give below permissions in your Menifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET"/>
My main class
public class MyLocationOnMap extends MapActivity {
private MapView mapView;
private MyLocationOverlay itemizedoverlay;
private LocationManager locationManager;
private String provider;
private MyLocationListener locationListener;
MyBroadCastreceiver myBroadCastreceiver;
/**
* My current Location <i>longitude</i>.
*/
static int longitude;
/**
* My current Location <i>latitude</i>.
*/
static int latitude;
/**
*My progress indicator.
*/
ProgressDialog loadingDialog;
public static final String INTENT_FILTER_TAG="my location broadcast receiver";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_location_on_map);
loadingDialog = new ProgressDialog(this);
loadingDialog.setTitle("Hot Spots!");
loadingDialog.setMessage("Please wait ...");
loadingDialog.setIndeterminate(true);
loadingDialog.setCancelable(false);
loadingDialog.show();
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
/**
* Get your location manager and Location Listener...
*/
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener=new MyLocationListener();
myBroadCastreceiver = new MyBroadCastreceiver();
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Log.i("GPS_Enabled", "GPS enable! listening for gps location.");
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, locationListener);
registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
Log.i("Network_Enabled", "Network enable! listening for Network location.");
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, locationListener);
registerReceiver(myBroadCastreceiver, new IntentFilter(INTENT_FILTER_TAG));
} else {
loadingDialog.dismiss();
Toast.makeText(this, "No Provider enable!", Toast.LENGTH_LONG).show();
}
}//End of onCreate......
/**
* My BroadCast Receiver, that is called when i get the location of user.
* #author Rupesh Yadav.
*
*/
class MyBroadCastreceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
//Remove location update when you get user`s location very first time.
locationManager.removeUpdates(locationListener);
//Remove the broadcast listener that update my location on map.
unregisterReceiver(myBroadCastreceiver);
GeoPoint point = new GeoPoint(latitude, longitude);
mapView.getController().animateTo(point);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = MyLocationOnMap.this.getResources().getDrawable(R.drawable.hs_mapoverlay);
itemizedoverlay = new MyLocationOverlay(drawable, MyLocationOnMap.this);
OverlayItem overlayitem = new OverlayItem(point, "Hello!", "My Current Location :)");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
loadingDialog.dismiss();
}
}
/**
* My Location listener...
*/
class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
latitude=(int) ((location.getLatitude())*1E6);
longitude=(int) ((location.getLongitude())*1E6);
//Send broadcast to update my location.
Intent sendLocationIntent=new Intent(INTENT_FILTER_TAG);
sendBroadcast(sendLocationIntent);
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
MyLocationOverlay class
public class MyLocationOverlay extends ItemizedOverlay<OverlayItem> {
Context mContext;
private ArrayList<OverlayItem> hsOverlays = new ArrayList<OverlayItem>();
public MyLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyLocationOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return hsOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return hsOverlays.size();
}
/**
* add new OverlayItem objects to map OverlayItem ArrayList.
*
* #param overlay
*/
public void addOverlay(OverlayItem overlay) {
hsOverlays.add(overlay);
populate();
}
/**
* Called when user clicks on map overlay.
*/
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
// return super.onTap(index);
OverlayItem item = hsOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
You can modify the Location Listener & Broadcasr Receiver according to your need.
I hope this will solve your problem.
Best regards!
I have used this class for detecting my lat & lon:
Hope this is useful for you too.
Example how to use:
GPSUtility.getInstance(Context).getLatitude();
GPSUtility.getInstance(CamPhotoModeAct.this).getLongitude()
public class GPSUtility {
public static final String TAG = "GPSUtility";
private Context ctx;
Timer timer1;
LocationManager lm;
LocationResult locationResult;
boolean gps_enabled=false;
boolean network_enabled=false;
private double latitude;
private double longitude;
private static SharedPreferences SHARED_PREF;
private static SharedPreferences.Editor EDITOR_SHARED_PREF;
private static GPSUtility this_instance;
public GPSUtility(Context ctx){
this.ctx = ctx;
SHARED_PREF = ctx.getSharedPreferences(ConstantsG.SHARED_PREF_FILE, Context.MODE_PRIVATE);
EDITOR_SHARED_PREF = SHARED_PREF.edit();
this.getLocation(innerLocationResult);
}
public static GPSUtility getInstance(Context ctx){
if(this_instance == null)
this_instance = new GPSUtility(ctx);
return this_instance;
}
public static void updateLocation(Context ctx){
GPSUtility.getInstance(ctx);//this writes the latitude and longitude in sharable preference file
}
public double getLatitude(){
String latitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LATITUDE,null);
if(latitudeStr == null){
latitude = 0.0;
}
else{
latitude = Double.parseDouble(latitudeStr);
}
return latitude;
}
public double getLongitude(){
String longitudeStr = SHARED_PREF.getString(ConstantsG.KEY_LONGITUDE,null);
if(longitudeStr == null){
longitude = 0.0;
}
else{
longitude = Double.parseDouble(longitudeStr);
}
return longitude;
}
private void updateWithNewLocation(Location location) {
if (location != null) {
latitude = location.getLatitude();
EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LATITUDE, String.valueOf(latitude) );
longitude = location.getLongitude();
EDITOR_SHARED_PREF.putString(ConstantsG.KEY_LONGITUDE, String.valueOf(longitude));
EDITOR_SHARED_PREF.commit();
}
}
public boolean getLocation(LocationResult result)
{
//I use LocationResult callback class to pass location value from GPSUtility to user code.
locationResult=result;
if(lm==null)
lm = (LocationManager) this.ctx.getSystemService(Context.LOCATION_SERVICE);
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
}
try {
network_enabled = lm
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Exception error: " + ex.getLocalizedMessage(), ex);
}
//Toast.makeText(context, gps_enabled+" "+network_enabled, Toast.LENGTH_LONG).show();
//don't start listeners if no provider is enabled
if(!gps_enabled && !network_enabled){
Toast.makeText(this.ctx, "You should enable gps or be connected to network.", Toast.LENGTH_LONG).show();
return false;
}
if(gps_enabled)
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
if(network_enabled)
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
timer1=new Timer();
timer1.schedule(new GetLastLocation(), 10000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
lm.removeUpdates(this);
lm.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
//Context context = getClass().getgetApplicationContext();
Location net_loc=null, gps_loc=null;
if(gps_enabled)
gps_loc=lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(network_enabled)
net_loc=lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if(gps_loc!=null && net_loc!=null){
if(gps_loc.getTime()>net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if(gps_loc!=null){
locationResult.gotLocation(gps_loc);
return;
}
if(net_loc!=null){
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
}
public static abstract class LocationResult{
public abstract void gotLocation(Location location);
}
LocationResult innerLocationResult = new LocationResult() {
#Override
public void gotLocation(Location location) {
updateWithNewLocation(location);
}
};
}
At the moment I'am working on project to messure frequency with gps :-). I like to get the gps information as soon as possible from GPS/Wifi. I also want to get it in the most highest frequency as possible. My goal is to messure a frequency from this data. At the moment I try it this way
final public void run() {
Looper.prepare();
while(gps){
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocationListener);
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
try {
Thread.sleep(100) ;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mLocationManager.removeUpdates(mLocationListener);
}
Looper.loop();
}//run
Is there a better way to get a faster "samplerate"?
From http://developer.android.com/guide/topics/location/obtaining-user-location.html:
You can control the frequency at which your listener receives updates with the second and third parameter—the second is the minimum time interval between notifications and the third is the minimum change in distance between notifications—setting both to zero requests location notifications as frequently as possible.
requestLocationUpdates gives you what you want. Not sure what you're trying to do with the while loop.
Get lat long using GPS in every 10 min.
// Des: Start Device's GPS and get current latitude and longitude
public void GPS() throws IOException {
// Des: This is a background service and called after every 10 minutes and fetch latitude-longitude values
background = new Thread(new Runnable() {
#Override
public void run() {
for (int i = 0; i < j; i++) {
if (ProjectStaticVariable.GPSExit == true ) {
try {
Thread.sleep(600000); //10 minutes
mainhandler.sendMessage(mainhandler.obtainMessage());
j++;
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
});
background.start();
mainhandler = new Handler() {
public void handleMessage(Message msg) {
// Check Internet status
isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
lat_long_Service_flag = true;
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener(getApplicationContext());
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 60000, 0, mlocListener);
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
}
};
}
// Des: Location Listener through which we get current latitude and longitude
public class MyLocationListener implements LocationListener {
public MyLocationListener(Context mContext) {}
public MyLocationListener(Runnable runnable) {}
#Override
public void onLocationChanged(Location loc) {
longitude = loc.getLongitude();
latitude = loc.getLatitude();
final_latitude = Double.toString(latitude);
final_longitude = Double.toString(longitude);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}