I've read the Google doc and this post notably the interesting #bendaf's answer, about managing Location settings, and everything works well.
Anyway one problem remains if the user first decide to not use its position and then decide later to activate it, the application is not trigged by this action so I don't know that I can request for periodic updates.
What did I miss here?
You can provide an AlertDialog every time user launches an app so that user can enable the location. But this will be a bit annoying because every time you have to deny to same thing.
Alternatively, you can use Preferences so that user can enable/disable the location
There is another better way to do it. Use LocationListener. It is for the sole purpose that you want to achieve.
public class XYZ Activity implements LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,10,this);
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
}
I think this is the right thing that you are looking for. It's the event way.
Happy Coding :)
#fralbo Although this thread is a tiny bit old, I just wanted to provide a solution for you, as I recently had to do something similar myself.
I would recommend implementing a BroadcastReceiver into your App, with the intent filter PROVIDERS_CHANGED..
This will trigger every time the Location/GPS Provider state changes - and you can use an if statement inside of the BroadcastReceiver's onReceive method, to determine whether or not your required conditions are met, and proceed accordingly.. For example, inside the onReceive method of the BroadcastReceiver, you can determine whether the PROVIDERS_CHANGED event has made the GPS become available (and to what degree) - and if it now meets the needs of your App, you can then call whichever Method within your App that is responsible for starting the required calls to the GPS engine, etc.
Here's an example of what the code might look like:
public class LocationReceiver extends BroadcastReceiver {
private final static String TAG = "[ LocationReceiver ]:";
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, "PROVIDERS_CHANGED has been detected - Firing onReceive");
// Retrieve the LocationManager
LocationManager locationManager =
(LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// Provide boolean references for Location availability types
boolean isGpsEnabled;
boolean isNetworkEnabled;
// Provide values to retrieve the Location availability
isGpsEnabled =
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled =
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
Log.i(TAG, "Detected - GPS: "+ isGpsEnabled + "NET: "+ isNetworkEnabled);
// If (for example), the GPS is ENABLED, start one of your Activities, etc.
if (isGpsEnabled) {
Intent startYourActivity =
new Intent(context.getApplicationContext(), YourActivity.class);
context.startActivity(startYourActivity);
}
}
}
I hope this helps! Better late than never :)
Happy coding!
Related
OLD QUESTION:
I'm trying to get my device's location coordinates and I've followed all the steps that I've found in multiple areas while researching. I've set up a LocationManager and used the requestLocationUpdates function that is tied to a LocationListener. However, the LocationListener does not respond. I've tried debugging as well as walking around outside in order for the onChangedLocation function to execute but nothing happens. In debugging the requestLocationUpdates function for my LocationManager is executed but the LocationListener is never executed.
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
textView = (TextView) findViewById(R.id.textView);
textView2 = (TextView) findViewById(R.id.textView2);
locationListener = new myLocationListener();
textView.setText("Longitude", TextView.BufferType.NORMAL);
textView2.setText("Latitude", TextView.BufferType.NORMAL);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, locationListener);
requestLocationUpdates
Above is the use of the requestLocationUpdates function.
private class myLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
//Log.e("Latitude: ", "" + location.getLatitude());
//Log.e("Longitude: ", "" + location.getLongitude());
if(location != null)
{
textView.setText(Double.toString(location.getLongitude()), TextView.BufferType.NORMAL);
textView2.setText(Double.toString(location.getLatitude()), TextView.BufferType.NORMAL);
}
else
{
textView.setText("No Location", TextView.BufferType.NORMAL);
textView2.setText("No Location", TextView.BufferType.NORMAL);
}
Toast.makeText(getApplicationContext(),"onLocationChanged Success",Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
myLocationListener
This is myLocationListener that implements LocationListener. I've added a little bit of extra code for testing purposes. The toast would never pop up so it appears as though this code is never executed. If anyone could help me out with this I would really appreciate it.
Thank you!
NEW QUESTION:
After continuing on developing in this page while waiting for a response I noticed that it takes about a minute for the location services to actually begin working. So, now my question is: how do I overcome the obstacle of a user having to wait to use the app? I've seen apps that use location based content and it does not take that long. I know that there is the getLastKnownLocation function but what if a user travels 50 miles before opening the app again? Any help on this would be appreciated. Thank you!
Each device which makes location request for gps, has to wait until gps hardware become warm. The wait time changes by device and where you stay. If you are inside a building, this time could take 1 minute or more.
To avoid wait, you can use getLastKnownLocation method, if returns a cached location, check location's date via getTime method. Determine yourself, is it old location by your scenario ?
if it's too old location, you have to make location request and wait.
1.In My application ,I want to track User Current Location Every 1 minute then Save in Local Database.Not getting Proper location Some times ,when user is Walking.
2.For finding location ,I want to use Google play Services API.
My Need:
Background Service Should get the location, save in local Database every minute.Even Application is Closed.
also with low Battery Usage.
I tried Some codes some methods are deprecated and not Working.
Please Suggest me any solution.
This is one of the way you can achieve it, make your service class like below
here,
with this ScheduledThreadPoolExecutor your service will be on in background
and you will need LocationManager
your SERVICE.class extend Service implements LocationListener, Runnable
private LocationManager mgr = null;
private ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
#Override
public void onCreate() {
//check gps is on/off
//get locationmanager
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//check if internet is on/off
setBeforeDelay15();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onLocationChanged(Location location) {
//re-execute at time you need with **scheduleAtFixedRate**
}
#Override
public void run() {
//here get the best location from two ways 1>gps and 2>network provider
//once you get this insert to database
//set delay then request call method again
}
#Override
public void onDestroy() {
//if locationmanager is not null then remove all updates
}
private void setDelay15() {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// Log.e("srop self by", "delay15");
startWork();
}
}, 300000);//120000
}
private void startWork() {
//check here for 1>gps and 2>network provider
//get location and save it
}
use this , when you require location in your application.
I'm planning to have a button in an activity which will start a service when clicked. However, GPS needs to be enabled for the service to do its work so I'd like to have the button disabled if GPS is disabled. Is there a way to get android to notify my activity when GPS is enabled/disabled so that I can enable/disable the button accordingly?
This link describes how to create a location listener:
http://blog.doityourselfandroid.com/2010/12/25/understanding-locationlistener-android/
I've copied the important parts down below in case the site goes down in the future. The first step is to create a LocationListener:
private final class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location locFromGps) {
// called when the listener is notified with a location update from the GPS
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
// Dim the button here!
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
// Brighten the button here!
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
}
Then you'll want to register that listener. This should probably go in your onCreate()
LocationListener locationListener = new MyLocationListener();
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 35000, 10, this.locationListener);
The second and third parameters in requestlocationupdates you should probably make huge so you don't get locationupdates since you don't really care about those, only provider enabled/disabled changes.
Please use this code to get the GPS status. use this code in the onResume of the activity
private LocationManager mLocationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
boolean GPSprovider = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
and according to the GPSProvider you can enable and disable the button.
try this
final String GpsProvider = Settings.Secure.getString(
getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (GpsProvider.equals(""){
//No GPS
}else{
//GPS available
}
I have been stuck on this problem for quite some time. I am working on an app that uses location quite extensively in several different Activities. Every example I have found uses a separate LocationListener in every Activity. This is not feasible in my situation.
I am wondering what is the most efficient way to keep track of the user's location across several activities. Right now I have created a service that implements LocationListener and uses a broadcast to update static lat and long fields in an Activity base class. This means that the service is always running, which isn't ideal. But if I shut down the service and restart it only when I need it, it takes time to get a good location. I need the location data in the Activity's onCreate(). It's the same if I try to implement it in the activity base class. If I constantly register the listener in onResume/onCreate and unregister it in onPause(), it takes too much time to start receiving updates. I also tried to create a service that I could bind to, so it only starts when I need a location. But I have the same problem, it takes too long to bind to the service and start getting updates.
The service that I am using now works but from everything I've read, I shouldn't be using a constantly running service for trivial things like this. But the whole point of the app is to provide relevant data based on the user's current location. So I have a service that just runs in the background and provides updates periodically. The one major problem that has caused me to reexamine the design at this point is that I recently discovered that onProviderEnabled() doesn't get called if the user starts the app without GPS turned on and then subsequently enables it. In this scenario the app has no way of recognizing that GPS was enabled so it can start listening for updates.
I thought I understood LocationManager and LocationListener from looking at the examples but I can't seem to apply it to this situation where I need location data in multiple Activities. Any help or advice would be greatly appreciated.
The way that I would typically implement this requirement is using a bound Service implementation, like the one in the Local Service Sample in the SDK Documentation. Obviously you're familiar with the advantage of the Service allowing you to create all the location code only once.
Accessing the Service through Bindings allows the Service to start and stop itself so it isn't running when your application isn't in the foreground (it will die as soon as no more Activities are bound). The key, IMO, to making this work well is to BIND the service in onStart() and UNBIND in onStop(), because those two calls overlap as you move from one Activity to another (Second Activity Starts before the First one Stops). This keeps the Service from dying when moving around inside the app, and only lets the service die when the entire application (or at least any part interested in location) leaves the foreground.
With Bindings, you don't have to pass the Location data in a Broadcast, because the Activity can call methods directly on the Service to get the latest location. However, a Broadcast would still be advantageous as a method of indicating WHEN a new update is available...but this would just become a notifier to the listening Activity to call the getLocation() method on the Service.
My $0.02. Hope that Helps!
I got the same problem and I tried to solve it with the good answer of Devunwired, but I had some troubles. I couldn't find a way to stop the service and when I finished my app the GPS-module was still running. So i found another way:
I wrote a GPS.java class:
public class GPS {
private IGPSActivity main;
// Helper for GPS-Position
private LocationListener mlocListener;
private LocationManager mlocManager;
private boolean isRunning;
public GPS(IGPSActivity main) {
this.main = main;
// GPS Position
mlocManager = (LocationManager) ((Activity) this.main).getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
// GPS Position END
this.isRunning = true;
}
public void stopGPS() {
if(isRunning) {
mlocManager.removeUpdates(mlocListener);
this.isRunning = false;
}
}
public void resumeGPS() {
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
this.isRunning = true;
}
public boolean isRunning() {
return this.isRunning;
}
public class MyLocationListener implements LocationListener {
private final String TAG = MyLocationListener.class.getSimpleName();
#Override
public void onLocationChanged(Location loc) {
GPS.this.main.locationChanged(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
GPS.this.main.displayGPSSettingsDialog();
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
This class is used in every Activity which needs the GPS coordinates. Every Activity has to implement the following Interface (needed for the communication):
public interface IGPSActivity {
public void locationChanged(double longitude, double latitude);
public void displayGPSSettingsDialog();
}
Now my main Activity looks like that:
public class MainActivity extends Activity implements IGPSActivity {
private GPS gps;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gps = new GPS(this);
}
#Override
protected void onResume() {
if(!gps.isRunning()) gps.resumeGPS();
super.onResume();
}
#Override
protected void onStop() {
gps.stopGPS();
super.onStop();
}
public void locationChanged(double longitude, double latitude) {
Log.d(TAG, "Main-Longitude: " + longitude);
Log.d(TAG, "Main-Latitude: " + latitude);
}
#Override
public void displayGPSSettingsDialog() {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
and a second one like that:
public class TEST4GPS extends Activity implements IGPSActivity{
private GPS gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.gps = new GPS(this);
}
#Override
public void locationChanged(double longitude, double latitude) {
Log.d("TEST", "Test-Longitude: " + longitude);
Log.d("TEST", "Test-Latitude: " + latitude);
}
#Override
protected void onResume() {
if(!gps.isRunning()) gps.resumeGPS();
super. onResume();
}
#Override
protected void onStop() {
gps.stopGPS();
super.onStop();
}
#Override
public void displayGPSSettingsDialog() {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
}
It's not as beautiful as the solution of Devunwired, but it works for me.
cya
You could have your service writing your lat & long coords to an sqlite db on change that way you dont have the service binding overhead and your coords will be accessible across all your activities.
Perhaps in your main activity you can check the GPS status and if it is turned off you can prompt the user to enable it. Once GPS is enabled start your service.
Here is a very simple and straightforward way to do it:
In your main activity:
private boolean mFinish;
#Override
public void onBackPressed() {
mFinish = true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFinish = false;
...
}
#Override
public void onPause(){
super.onPause();
if (mFinish) {
// remove updates here
mLocationManager.removeUpdates(mLocationListener);
}
}
This will only remove the updates listener if you press Back in your main activity, but otherwise stay on.
It's not the best way to do it, but it's a simple copy-paste solution.
Make sure you don't call location listener if it's already running (for example on screen rotate), otherwise you'll end up with multiple listeners running in the background.
I'm using the code shown below to get an updated value for location every time a button is clicked. When my activity is resumed I get an update every second, so that when I call getLastKnownLocation I expect to have a location that have been updated in the last second.
Is that the correct way to do that?
I would expect the onLocationChanged event to be triggered every time I execute a 'geo fix' command (or max after 1s since I request update every 1s), but it's only triggered the first time. Why?
Any help/suggestion welcome!
Thanks
package org.digitalfarm.atable;
...
public class Atable extends Activity {
private Button mSearchButton;
private TextView mytext;
private LocationManager locationManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSearchButton = (Button)this.findViewById(R.id.button);
mytext = (TextView) findViewById(R.id.dude);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
mSearchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
}
});
}
//Start a location listener
LocationListener onLocationChange=new LocationListener() {
public void onLocationChanged(Location loc) {
//sets and displays the lat/long when a location is provided
String latlong = "Lat: " + loc.getLatitude() + " Long: " + loc.getLongitude();
mytext.setText(latlong);
}
public void onProviderDisabled(String provider) {
// required for interface, not used
}
public void onProviderEnabled(String provider) {
// required for interface, not used
}
public void onStatusChanged(String provider, int status,
Bundle extras) {
// required for interface, not used
}
};
//pauses listener while app is inactive
#Override
public void onPause() {
super.onPause();
locationManager.removeUpdates(onLocationChange);
}
//reactivates listener when app is resumed
#Override
public void onResume() {
super.onResume();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,100.0f,onLocationChange);
}
}
The time, specified in requestLocationUpdates is the shortest possible time interval for which a maximum of one update will occur. So you have registered for at most one update every second, but the actual update may take more that that to occur, and, furthermore, no guarantee is given for that.
From the documentation:
minTime - the minimum time interval for notifications, in milliseconds. This field is only used as a hint to conserve power, and actual time between location updates may be greater or lesser than this value.
Try to set that time interval to 0 and if there are no other problems (although it all seems fine to me), you should start getting the updates "as frequently as possible".