Notification if user close to location - android

In my app I have a list of round 9 places with the associative lat long positions, and the end goal is to notify the user if they are within about half a mile of any of the locations.
What would be the best way to do this? This is what I have so far.
distanceFromListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
List<JSONObject> centres = sortVenuesByNearest(location);
Log.d("FUApp", "distanceFromListener setting location");
haveLocation = true;
theLocation = location;
float accuracy = location.getAccuracy();
for (JSONObject centre : centres) {
try {
Double distance = Double.valueOf(centre.getString("distanceTo"));
String name = centre.getString("name");
Integer venueID = Integer.valueOf(centre.getString("id"));
if (distance < 804.672) {
Bundle mBundle = new Bundle();
Double miles = (distance * 0.00062137);
DecimalFormat df = new DecimalFormat("#.##");
String miles2 = df.format(miles);
mBundle.putString(ExtraKeyCentreName, name);
mBundle.putString(ExtraKeyCentreDist, miles2 + " miles away");
mBundle.putString(ExtraKeyCentreJSON, centre.toString());
mBundle.putString(ExtraKeyCentrePostcode, "none");
sendNotification(ActivityCentrePage.class, "Visit " + name, "You're half a mile from " + name + ". Why not come for a visit?", R.drawable.ic_launcher, venueID, mBundle);
} else {
cancelNotification(venueID);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
Boolean notify_if_close = sp.getBoolean(SettingsNotifyIfClose, true);
if (notify_if_close) {
locationService.requestLocationUpdates(LocationManager.GPS_PROVIDER, 50, 100, distanceFromListener);
}
That works, but if the user cancels a notification saying there close, when the location is next updated it will pop up again, which will get annoying. Would a suitable alternative be put a big minTime, say half an hour on the requestLocationUpdates?

What would be the best way to do this?
Use geofences with the LocationClient from the Play Services SDK, or try proximity alerts with LocationManager.

Use a service for tracking coordinates...
try this link, it may help u..
http://www.androidhive.info/2012/07/android-gps-location-manager-tutorial/

Related

Android - Can't refresh user location on activity launch

I'm stuck trying to refresh the user's location.
In my app, I start the map marking user's current location, but locationManager.getLastKnownLocation() is returning a different location
because it uses a cache location.
How can I compare the last known location with the current location so I can mark the correct position on the map in the callback OnMapReady?
Every example I found in StackOverflow is using LocationListener.onLocationChanged() method, but I need to refresh the location (if needed) on activity launch.
Code:
private static final String TAG_MAP_LOAD_FAILED = "FAIL LOADING MAP STYLE";
private static final String TAG_MAP_PARSING_FAILED = "FAIL PARSING MAP STYLE";
private GoogleMap mMap;
private LatLng mMyCoordinates;
private LocationManager mLocationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLocationManager = (LocationManager) getContext().getSystemService(Context.LOCATION_SERVICE);
getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
try{
boolean success = googleMap.setMapStyle(MapStyleOptions.loadRawResourceStyle(getContext(), R.raw.style_mapjson));
if(!success){
Log.e(TAG_MAP_PARSING_FAILED, "Failed parsing JSON Style");
}
}catch (Resources.NotFoundException ex){
Log.e(TAG_MAP_LOAD_FAILED, "Can't find style. Error:", ex);
}
mMap.setIndoorEnabled(false);
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(mMyCoordinates);
markerOptions.title("Marker in my location");
mMap.addMarker(markerOptions);
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(mMyCoordinates, 15);
mMap.moveCamera(cameraUpdate);
mMap.getUiSettings().setRotateGesturesEnabled(false);
}
#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) {
}
OBS: I cleaned up the code because it was getting full of unsuccessful attempts. Just showing how it is structured.
Should I use FusedLocation instead?
The last known location has a timestamp associated with it, which can be quite some time in the past. Just do an age comparison with the last known location's timestamp with the max age you'd allow, and request an update when needed. Here is a quick and dirty example:
private static long MAX_TIME = 60 * 60 * 1000; //Update if location is older than one hour
#Override
public void onResume() {
super.onResume();
Location location = mLocationManager.getLastKnownLocation(YOUR_PROVIDER_HERE); //GPS or Network
boolean shouldUpdateLocation = false;
if (location != null) {
long elapsedTime = System.currentTimeMillis() - location.getTime();
if (elapsedTime >= MAX_TIME) {
shouldUpdateLocation = true;
}
}
else {
shouldUpdateLocation = true;
}
if (shouldUpdateLocation) {
//TODO: Request location update here.
}
}
You don't want to be requesting location updates every time the activity is brought up, so set up a reasonable MAX_TIME for this.

What is the best way to identify places on gps?

i'm trying to develop application with a gps that can know if i arrive at or leave a specific place.
I.E if i am at home so, the application know that and if i leaving my home the application know that too. or if i want to set the radius of my home. but i think the problem is that when i trying to running the appliction and search places every x time it could kill my battery.
what is the best solution for that action? should i using services too?
here is the class i made to get the place and the coordinates:
public class LocationMap extends Service implements LocationListener {
public static final String LOG = "locationLogger";
Context context;
LocationManager manager;
Location location;
public static final int REFRESH = 1000*1;
public static final int DISTANCE = 1*1;
double lat,lng;
boolean isGps,isWiFi;
public LocationMap(Context context) {
this.context = context;
getLocation();
}
private Location getLocation(){
try {
manager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER,REFRESH,DISTANCE,this);
//Check who is on WiFi or GPS
isWiFi = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);Log.d(LOG, "Wifi?="+isWiFi);
isGps = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);Log.d(LOG, "Gps?="+isGps);
Log.d(LOG, "manager is not null?="+manager);
if (manager != null) {
if(isGps){
Log.d(LOG, "get last location from Gps");
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}else
if(isWiFi){
Log.d(LOG, "get last location from WiFi");
location = manager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
Log.d(LOG, "lat="+lat +" lng="+lng);
}
}
} catch (Exception e) {
}
return location;
}
public String getPlace(){
String placeName = "No place found, check your gps setting";
try {
Geocoder geocoder = new Geocoder(context);
List<Address> address =geocoder.getFromLocation(getLat(), getLng(), 1);
String country = address.get(0).getCountryName();
String city = address.get(0).getLocality();
String street = address.get(0).getAddressLine(0);
placeName = country+", "+city+", "+street;
} catch (IOException e) {
e.printStackTrace();
}
return placeName;
}
public double getLng(){
return lng;
}
public double getLat() {
return lat;
}
#Override
public void onLocationChanged(Location location) {
}
#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 IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
sorry about my english. hope you understand me :)
That depends on your accuracy needed.
If the desired range is about 1 - 3km then there is a battery saving solution, I will not further explain here. (Using the devices Network locationg procider)
For accuracy much better there is no way around using GPS always on,
which at my iphone 4 lasts about 8 hours.
Detection if arrival is simply done via entering inside a circle, defined by lat,lon, radius.
Inside circle is calculated by:
boolean isInside = currentLocation.distanceTo(circleCenterLongitude, circleCenterLatitude) < radiusMeters.

Not getting Lat and Long through either GPS or Network

I am trying to get location using GPS provider or Network provider but i didn't get location from either GPS or Network.
Here is my code which was working fine some days ago but now it's not working.
I don't understand where i am wrong because all permission are already added in AndroidManifest.xml.
Here is the code which helpful for you to understand.
public class SearchDishoom extends Header implements LocationListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchdish);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000000, 100, this);
locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// if gps provider is not enable then popup alertbox
buildAlertMessageNoGps();
} else {
// if gps is one then start searching
locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
}
/*
* Get location (lat-long) from sharedpreference to further use
*/
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
String userLocationLat1 = prefLocation.getString("Lat", String.valueOf(0));
String userLocationlong1 = prefLocation.getString("Long", String.valueOf(0));
String address = prefLocation.getString("Address", "Location not found not found");
userLocationLat = Double.parseDouble(userLocationLat1);
userLocationlong = Double.parseDouble(userLocationlong1);
// set lat-long value in getset class for use of another activity
gs = new GetSet();
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
if (userLocationLat == 0 && userLocationlong == 0 && address.equals("")) {
/*
* if lat-long is 0 or null then start searching using
* GPS Provider or Network Provider
*/
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
buildAlertMessageNoGps();
} else {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000000,100, locationListenerGps);
}
} else {
// set lat-long value in getset class for use of another activity
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
setLocationName(userLocationLat, userLocationlong);
}
}
Here is override onLocationchanged():
#Override
public void onLocationChanged(Location location) {
userLocationLat =location.getLatitude();
userLocationlong =location.getLongitude();
prefLocation = getSharedPreferences("myLocation", MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = prefLocation.edit();
prefsEditor.putString("Lat", String.valueOf(userLocationLat));
prefsEditor.putString("Long", String.valueOf(userLocationlong));
gs.setLatitude(userLocationLat);
gs.setLangitude(userLocationlong);
List<Address> addresses;
try {
addresses = new Geocoder(SearchDishoom.this, Locale.getDefault())
.getFromLocation(userLocationLat, userLocationlong, 1);
Address obj = addresses.get(0);
add = obj.getAddressLine(0);
city = obj.getLocality();
addressString = add + "," + city;
gs.setCurrentAddressString(addressString);
prefsEditor.putString("Address", addressString);
prefsEditor.commit();
tvLocation.setText(add + "," + city);
} catch (IOException e) {
showToast("Unable to find location");
}
}
Even i am not getting location using Geocoder, If i enter city name then it show me "Unable to find location".
Here is trick, GeoCoder is working on Emulator but not working on phone(i tried 2 different handset).
My project is build in API 17 and no any logcat error.
Please give me any hint or reference.
Maybe you should check "location access" settings and allow access to your location?..
While I cant immediately tell whats wrong with your code, you should consider maybe using a location library and let others do the heavy lifting. See: https://code.google.com/p/little-fluffy-location-library/

How to store a value from a textbox android?

i am developing an gps program in that i am getting gps values for every 5 minutes,
and it is working great, but i have to store the values which i get. it has been refreshed for every 5 minutes and i have only one text view so that it deletes the old values when the new one is refreshed.
this is my code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//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)); 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, 60000, 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;
}
Thank you.
You can store your Textview's value into a file for persistance storage. Study my answer properly, I am adding a file store method in your existing code,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.sendBroadcast(intent);
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.sendBroadcast(poke);
}
{
//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)); 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, 60000, 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");
// I have added this line
appendData ( 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;
}
// method to write in file
public void appendData(String text)
{
File dataFile = new File("sdcard/gpsData.txt");
if (!dataFile.exists())
{
try
{
dataFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(dataFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You need to write following permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Well you have plenty of persistence options, but in this case the best is using SharedPreferences
No one can say for sure without knowing exactly what you need to do with the saved data. ArrayList is a good option if you need to store it temporarily. You can create a new ArrayList then put the value in there at the same time that you use it in setText(). If you want something permanent then you will probably want to store it in a DB or a file. Check out Storage Options
Also, in this case, a good idea may be to store it in an ArrayList temporarily then use that list to transfer them to a file or DB for permanent storage if that's what you want
Another way to store it temporarily, and possibly save somewhere later would be a HashMap. Maybe something in the form of HashMap<String, HashMap<String, String>>. Since we don't know your exact intentions with the data, examples could be endless but maybe this will give you a good starting point so you can decide what will work best for you then you can find many examples all over SO and the Google for your choice

Android: get current location from best available provider

I have some Android code that needs to get the best available location QUICKLY, from GPS, network or whatever is available. Accuracy is less important than speed.
Getting the best available location is surely a really standard task. Yet I can't find any code to demonstrate it. The Android location code expects you to specify criteria, register for updates, and wait - which is fine if you have detailed criteria and don't mind waiting around.
But my app needs to work a bit more like the Maps app does when it first locates you - work from any available provider, and just check the location isn't wildly out of date or null.
I've attempted to roll my own code to do this, but am having problems. (It's inside an IntentService where an upload happens, if that makes any difference. I've included all the code for info.) What's wrong with this code?
#Override
protected void onHandleIntent(Intent arg0) {
testProviders();
doUpload();
}
private boolean doUpload() {
int j = 0;
// check if we have accurate location data yet - wait up to 30 seconds
while (j < 30) {
if ((latString == "") || (lonString == "")) {
Log.d(LOG_TAG, "latlng null");
Thread.sleep(1000);
j++;
} else {
Log.d(LOG_TAG, "found lat " + latString + " and lon " + lonString);
break;
}
//do the upload here anyway, with or without location data
//[code removed for brevity]
}
public boolean testProviders() {
Log.e(LOG_TAG, "testProviders");
String location_context = Context.LOCATION_SERVICE;
locationmanager = (LocationManager) getSystemService(location_context);
List<String> providers = locationmanager.getProviders(true);
for (String provider : providers) {
Log.e(LOG_TAG, "registering provider " + provider);
listener = new LocationListener() {
public void onLocationChanged(Location location) {
// keep checking the location - until we have
// what we need
//if (!checkLoc(location)) {
Log.e(LOG_TAG, "onLocationChanged");
locationDetermined = checkLoc(location);
//}
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
locationmanager.requestLocationUpdates(provider, 0,
0, listener);
}
Log.e(LOG_TAG, "getting updates");
return true;
}
private boolean checkLoc(Location location) {
float tempAccuracy = location.getAccuracy();
int locAccuracy = (int) tempAccuracy;
Log.d(LOG_TAG, "locAccuracy = " + locAccuracy);
if ((locAccuracy != 0) && (locAccuracy < LOCATION_ACCURACY)) {
latitude = location.getLatitude();
longitude = location.getLongitude();
latString = latitude.toString();
lonString = longitude.toString();
return true;
}
return false;
}
public void removeListeners() {
// Log.e(LOG_TAG, "removeListeners");
if ((locationmanager != null) && (listener != null)) {
locationmanager.removeUpdates(listener);
}
locationmanager = null;
// Log.d(LOG_TAG, "Removed " + listener.toString());
}
#Override
public void onDestroy() {
super.onDestroy();
removeListeners();
}
Unfortunately, this finds the network provider, but only ever outputs latlng null 30 times - it never seems to get a location at all. I never even get a log statement of locationChanged.
It's funny, because from ddms I can see output like:
NetworkLocationProvider: onCellLocationChanged [305,8580]
NetworkLocationProvider: getNetworkLocation(): returning cache location with accuracy 75.0
seeming to suggest that the network provider does have some location info after all, I'm just not getting at it.
Can anyone help? I think working example code would be a useful resource for the Android/StackOverflow community.
You are definitely trying to do this the hard way. Here are some snippets from a new app I am working on. It uses Criteria to get all providers capable of returning a fine level of accuracy without a cost.
If no providers are enabled a dialog is displayed that prompts the user to turn on their location settings. If the user hits ok an Intent is actually fired that sends them to the settings on their phone. If there are providers enabled the app takes the most recent last known location from any of the enabled providers. For my app I just need to know what general area the user is in and it's likely that the last known location is from their home area.
If providers are enabled the loop also requests location updates as quickly as possible. This is ideal for my app but you can change this to conserve battery my modifying the arguments to the requestLocationUpdates method.
The optimization that this code has that the examples on the Android app don't really show is that all of the enabled providers are started simultaneously. All of the providers will return separate updates on to the onLocationChanged method. In my app I remove the location listener after one of the providers returns a location with a good enough accuracy.
Start Location Updates:
void getCurrentLocation() {
List<String> providers = locationManager.getProviders(criteria, true);
if (providers != null) {
Location newestLocation = null;
for (String provider : providers) {
Location location = locationManager.getLastKnownLocation(provider);
if (location != null) {
if (newestLocation == null) {
newestLocation = location;
} else {
if (location.getTime() > newestLocation.getTime()) {
newestLocation = location;
}
}
locationManager.requestLocationUpdates(provider, 0, 0, this);
}
}
} else {
LocationDialogFragment dialog = new LocationDialogFragment();
dialog.show(getSupportFragmentManager(),
LocationDialogFragment.class.getName());
}
}
Receive Location Update:
#Override
public void onLocationChanged(Location location) {
float bestAccuracy = -1f;
if (location.getAccuracy() != 0.0f
&& (location.getAccuracy() < bestAccuracy) || bestAccuracy == -1f) {
if (location.getAccuracy() < Const.MIN_ACCURACY) {
locationManager.removeUpdates(this);
}
}
bestAccuracy = location.getAccuracy();
}
Location Settings Dialog:
public class LocationDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.location_dialog_message)
.setPositiveButton(R.string.location_dialog_positive_button,
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent settingsIntent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(settingsIntent);
}
})
.setNegativeButton(R.string.location_dialog_negative_button,
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(),
R.string.no_location_message, Toast.LENGTH_LONG)
.show();
}
});
return builder.create();
}
}
Thread.sleep() in production code is a serious code smell IMHO. If you find you're having to do that, you're probably doing something that's not supposed to work that way. In this case, I think it's the source of your problem -- you're not letting Android go back to process this thread's message queue to dispatch any location updates it finds. I suspect an IntentService is just not going to work for your scenario.

Categories

Resources