I'm trying to get the devices location by getting all listeners:
LocationManager locationManager = (LocationManager) myContext.getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
for (String s : locationManager.getAllProviders()) {
locationManager.requestLocationUpdates(s, checkInterval,
minDistance, new LocationListener() {
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onLocationChanged(Location location) {
// if this is a gps location, we can use it
if (location.getProvider().equals(
LocationManager.GPS_PROVIDER)) {
doLocationUpdate(location, true);
stopGPS();
}
}
#Override
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
});
gps_recorder_running = true;
}
// start the gps receiver thread
gpsTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
Location location = getBestLocation();
doLocationUpdate(location, false);
if ((System.currentTimeMillis()-startMillis)>maxCheckTime){stopGPS();}
}
}, 0, checkInterval);
}
The problem comes when I want to stop the Listeners. I tried to cancel the timer:
gpsTimer.cancel();
But it doesn't stop the Listeners. I think I have to use locationManager.removeUpdates, but how do I stop all Listeners?
Thanks
You must keep a list of all the location listeners you register and then call unregister with each of them when you are done. Either that or just reuse the same listener for each call and then unregister it once.
Edit
//Make the following line a field in your class
List<LocationListener> myListeners = new ArrayList<LocationListener>();
for (String s : locationManager.getAllProviders()) {
LocationListener listener = new LocationListener() { .... }; //I'm cutting out the implementation here
myListeners.add(listener);
locationManager.requestLocationUpdates(s, checkInterval,
minDistance, listener);
}
Related
There is any solution to check if user disable GPS in settings?
I open my app, open top toolbar of android system, disable GPS and close this toolbar. In this moment I want to app check if status of GPS was changed.
I use check if GPS is active in onResume(), but this solution works only when user enable GPS, when disable onResume() is not called.
Any ideas?
Edit:
This is may class:
public class PrivacyActivity extends BaseActivity implements GpsStatus.Listener, LocationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_privacy);
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onGpsStatusChanged(int event) {
switch (event) {
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Toast.makeText(this, "ads", Toast.LENGTH_LONG).show();
break;
case GpsStatus.GPS_EVENT_FIRST_FIX:
Toast.makeText(this, "ads1", Toast.LENGTH_LONG).show();
break;
}
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "ads2", Toast.LENGTH_LONG).show();
}
}
and when I disable gps I didn't see toast.
You can use the LocationListener class
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
Log.i("Example", "GPS is ON");
}
public void onProviderDisabled(String provider) {
Log.i("Example", "GPS is OFF");
}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
You can get more info in http://developer.android.com/guide/topics/location/strategies.html
Reference the locationListener first.
LocationListener locationListener;
locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
LatLng myPlace = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(myPlace).title("me"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(myPlace));
mMap.animateCamera(CameraUpdateFactory.zoomTo(8.0f));
}
#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);
}
};
onProviderDisabled method will be fired if the user has disabled GPS from settings.
The intent inside the method will take the user to location settings directly.
Tested and works fine.
On this code i want to get the gps location every 3 seconds. but when i run this program on my device it tells me that latitude and longitude are both 0 every time. how should i handle this problem?
and what is the looper task ?? it gives me error when i donot use it
public class LocationService extends Service {
final static String TAG = "MyService";
double latitude ;
double Longitude ;
LocationManager lm;
LocationListener ll;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Log.d(TAG, "onCreate");
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread() {
public void run() {
Looper.prepare();
while(true){
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
ll = new MyLocationListener();
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,
0, 0, ll);
//when i log here , it gives me wronganswer
Log.d(TAG,Double.toString(latitude));
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Log.d(TAG, "OnDestroy");
super.onDestroy();
}
class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location location) {
//when i log here , it gives me correct answer
double lat = location.getLatitude();
double lon = location.getLongitude();
latitude = lat;
Longitude = lon;
}
#Override
public void onProviderDisabled(String arg0) {
}
#Override
public void onProviderEnabled(String arg0) {
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
}
};
}
When you get location from GPS, it can take some time, because GPS module needs to find satellites. So you need to wait couple or few minutes while GPS module find satellites. If WI-FI location provider available you can get location more quick.
Additional info about location providers you can find here: http://developer.android.com/guide/topics/location/strategies.html
Since Android has
GPS_PROVIDER and NETWORK_PROVIDER
you can register to both and start fetch events from onLocationChanged(Location location) from two at the same time. So far so good. Now the question do we need two results or we should take the best. As I know GPS_PROVIDER results have better accuracy than NETWORK_PROVIDER.
for example you have location listener:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
//here you get locations from both providers
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
YOu need to do something like that:
LocationManager lm = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListener);
but before registering you need to check is these providers available on this device, like that:
boolean network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
boolean gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
Lets say that i have an object that asynchronously will be seted (an user GPS position for example).
Is there a way to only call a method in an Activity when this object is not null?
If you simply want to call a method if some object is not null then:
if (myObject != null) { callMyActivityMethod()}
Based on your updated information, you only want to call the method once you have received a location from the GPS.
A LocationListener is used for receiving notifications from your LocationManager.
Create a LocationListener and pass it in your requestForLocationUpdates(). It will then notify you when a new location has been received. For Example:
LocationListener locListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
callMyActivityMethod();
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
};
...
requestLocationUpdates(provider, minTime, minDistance, locListener);
...
Hie i tried to implement this codes in my application but it doesnt work , i dont know where i went wrong.
basically, when i launch the sample of the device location. it doesnt show me where is my current location and i dont see any blue dots that resembles the current location i am at.
the only thing that i see is the map . just a plain zoom out map.
I would be really thankful if someone who could help me out on how to get the current location with the blue dots that is displayed on the map..
this is my MainActivity.class
public class HelloWorld extends Activity {
MapView mMapView = null;
ArcGISTiledMapServiceLayer tileLayer;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Retrieve the map and initial extent from XML layout
mMapView = (MapView) findViewById(R.id.map);
mMapView.addLayer(new ArcGISTiledMapServiceLayer(
"http://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer"));
mMapView.setOnStatusChangedListener(new OnStatusChangedListener() {
public void onStatusChanged(Object source, STATUS status) {
if (source == mMapView && status == STATUS.INITIALIZED) {
LocationService ls = mMapView.getLocationService();
ls.setAutoPan(false);
ls.start();
}
}
});
}
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
}
this is a code that draws my location every 1 second via provider and GPS .
let's first declare variables :
private GraphicsLayer myGraphicalLayer;
MapView mMapView;
ArcGISLocalTiledLayer baseLayer;
private LocationManager mlocManager;
private LocationListener mlocListener;
in onCreate function WE CALL LocationListener:
mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mlocListener);
// loading the map
mMapView = (MapView) findViewById(R.id.localMap);
baseLayer = new ArcGISLocalTiledLayer(basemapurl);
mMapView.addLayer(baseLayer);
// defining my position layer
myGraphicalLayer = new GraphicsLayer();
then a function to draw my location :
private void SetMyLocationPoint(final double x, final double y) {
PictureMarkerSymbol myPin = new PictureMarkerSymbol(getResources().getDrawable(
R.drawable.mylocation_icon));
Point wgspoint = new Point(x, y);
Point mapPoint = (Point) GeometryEngine.project(wgspoint, SpatialReference.create(4326),
mMapView.getSpatialReference());
Graphic myPinGraphic = new Graphic(mapPoint, myPin);
try {
myGraphicalLayer.removeAll();
} catch (Exception e) {
e.printStackTrace();
}
myGraphicalLayer.addGraphic(myPinGraphic);
myGraphicalLayer.setVisible(true);
mMapView.addLayer(myGraphicalLayer);
}
make internal class that implements MyLocationListener to get you instant location, and let it call the function named SetMyLocationPoint like this way :
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
SetMyLocationPoint(loc.getLongitude(), loc.getLatitude());
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(getApplicationContext(), "provider enabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "provider disabled", Toast.LENGTH_SHORT)
.show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
You need to use your own location manager or the location client to get the device's current location and then you will have to add that point on the map.
Your map should be in a MapFragment.
Get the googleMap object from the fragment and then add your custom blue dot on it.
LocationManager locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
}
}
#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
}
};
The above code gets you the location in onLocationChanged method.
Note: i have used GPS_PROVIDER to get the location.
There are other ways to get the current location too.
i'm new in java/android app and i'm creating an app that uses user-location. I want the location to be updated at the begining of the app.
The problem is that my location class is an activity and i don't want to show another contentview for this class.
Actually, i want the location thing to be done in background, without changing the UI, in a separated class.
Is it possible? How?
Thanks :P
There is no need to put the location in a different activity, the LocationManager already does it in the background:
public void getLocation(){
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
gpsLocationListener = 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) {
//do something with the new location
if (location != null)
gpsLocation = location;
}
};
gpsLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1, 0, gpsLocationListener);
}
Using the LocationManager you should be able to use what ever kind of activity (or service) you want.