Remove Location Listener - android

I want after open dialog and click on location button, detect user's location and show user's location and then user dismiss dialog, location listener removes and not get location from onLocationChanged, I try used locationManager.removeUpdate(locListener)on override dismiss but not any chance and location after dismiss again shows! why? How can i detect user's location after show dialog and after detect location, location listener remove? Thanks
EDIT:
public class DialogTest extends Dialog implements
android.view.View.OnClickListener {
Context context;
LocationManager locationManager;
LocationListener locationListener;
Location location;
public DialogTest(Context context) {
super(context);
// TODO Auto-generated constructor stub
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.context = context;
setContentView(R.layout.profile_dialog);
getWindow().setBackgroundDrawableResource(R.drawable.background_dialog);
firstAccessLocation=true;
setCancelable(true);
initialize();
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
findAddress();
}
private void findAddress() {
// if (gpsCheckBox.isChecked()) {
locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 0,
0, locationListener);
locationManager.requestLocationUpdates(
locationManager.NETWORK_PROVIDER, 0, 0, locationListener);
// }
}
private void stopTracking(){
if(locationManager!=null){
locationManager.removeUpdates(locationListener);
}
}
#Override
public void dismiss() {
// TODO Auto-generated method stub
stopTracking();
gpsTurnOff();
super.dismiss();
}
public class GPSLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location loc) {
// TODO Auto-generated method stub
if(location!=null)
Log.e("location", location.getLatitude()+"");
location = loc;
if (location != null&& firstAccessLocation) {
setAddress(location.getLatitude(), location.getLongitude());
firstAccessLocation=false;
}
Toast.makeText(context, "changed", Toast.LENGTH_LONG).show();
Log.e("location", "changed");
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}

In new code you should use LocationClient rather then LocationManager. It's more efficient in getting the location with minimal energy(battery drain) with greater accuracy. Look here LocationClient vs LocationManager. With LocationClient established you can call getLastLocation() which provide you last location and doesn't start cyclic location updates.
If you want to stick with LocationManager use requestSingleUpdate (String provider, LocationListener listener, Looper looper) method to get only one newest location from it.

Related

Why activate GPS is not enough to get user's position?

I'm working on an Android project which give the user the possibility to turn on his GPS. His position is requested to launch the application.
After activation, I use getLastKnownLocation of LocationManager but this method returns a Location indicating the data from the last known location fix obtained from the given provider. The doc explains that this can be done without starting the provider. Note that this location could be out-of-date, for example if the device was turned off and moved to another location.
However the user activate localization services. So turn on the GPS is not enough to launch the GPS as it's done by Google Maps by showing an icon at the top of the device and retrieving GPS coordinates. This icon doesn't appear when my application gives the user the possibility to activate the GPS (seems weird).
Theards I already read use getLastKnownLocation method after choosing the best provider. Questions are did I miss something after turning on the GPS services? Did the GPS is automatically launch when the GPS is activated?
I already ask this, but not enough answer.
for showing blue dot icon on map use this line
map_fragment.setMyLocationEnabled(true);
use this code to get location where you want to get location
GPSTracker gps = new GPSTracker(this);
Double latiDouble = gps.getLatitude();
Double loDouble = gps.getLongitude();
create a class GPSTracker and add this code
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
boolean isGPSEnabled=false;
boolean isNetworkEnabled=false;
boolean canGetLocation=false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES=10; //10 meters
private static final long MIN_TIME_BW_UPDATES=1000*60*1; //1 minute
private LocationManager locationManager;
public GPSTracker(Context context)
{
this.mContext=context;
getLocation();
}
public Location getLocation()
{
locationManager=(LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled)
{
//showSettingAlert();
}
else
{
this.canGetLocation=true;
if(isGPSEnabled)
{
if(location==null)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
}
if(locationManager != null)
{
location=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
if(isNetworkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
if(locationManager!=null)
{
location=locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!=null)
{
latitude=location.getLatitude();
longitude=location.getLongitude();
}
}
}
}
return location;
}
public void stopUsingGPS()
{
if(locationManager!=null)
{
locationManager.removeUpdates(GPSTracker.this);
}
}
public double getLatitude()
{
if(location != null)
{
latitude=location.getLatitude();
}
return latitude;
}
public double getLongitude()
{
if(location != null)
{
longitude=location.getLongitude();
}
return longitude;
}
public boolean canGetLocation(){
return this.canGetLocation;
}
public void showSettingAlert()
{
AlertDialog.Builder alertDialog=new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS Settings");
alertDialog.setMessage("GPS is not enabled .Do you want to go to settings menu ?");
alertDialog.setPositiveButton("Settings",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Intent i=new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(i);
}
});
alertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
}
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
No, turning on GPS is not enough, you also need a Location Listener to listen to updates of position.
Something like in Location Strategies
// 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) {}
public void onProviderDisabled(String provider) {}
};
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);

Implementing Android LocationListener in a widget

I am working on a widget for Android, which displays your current location. To get the current latitude and longitude I have the following code:
public class LocationInfo extends Activity {
RemoteViews remoteViews;
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocationListener locationListener = new myLocationListener();
LocationProvider locationProvider = locationManager.getProvider(LocationManager.NETWORK_PROVIDER);
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
class myLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
if(location != null)
{
double Long = location.getLongitude();
double Lat = location.getLatitude();
remoteViews.setTextViewText(R.id.widget_textview3, Double.toString(Long));
}
else {
remoteViews.setTextViewText(R.id.widget_textview3, "LOADING...");
}
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
}
However, I get an error at the arguments of requestLocationUpdates. It says "Syntax error on tokens, VariableDeclarator expected instead" at 0,0, locationListener.
Also, this is a separate class. How would I then run this in my widget? Something like:
LocationInfo locationProvider = new LocationInfo();
LocationProvider.run();
maybe? Again, any help would really be appreciated!
You are not allowed to execute
locationManager.requestLocationUpdates(locationProvider, 0, 0, locationListener);
outside of methods.
Just move in to, for example, onCreate of Activity.
Good luck

Android: How to get GPS data without using a MapView?

I am trying to get GPS data without using map view.The code that I have below is from O'Rielly's Programming Android book and is supposed to work but is not. I am using an Android 2.2.1 phone and the app closes immediately after it starts.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
tvLattitude.setText(Double.toString(loc.getLatitude()));
tvLongitude.setText(Double.toString(loc.getLongitude()));
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
private class DispLocListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
tvLattitude.setText(Double.toString(location.getLatitude()));
tvLongitude.setText(Double.toString(location.getLongitude()));}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
lm.removeUpdates(locListenD);}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);}
Perhaps you need to add the permissions
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
to your manifest?
Well, I set up a similar project and found a problem with your code: in onCreate you immediately try to set the location from previous locations (which on first run obviously wouldn't be available). I erased those lines and the code seems to run fine
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tvLattitude = (TextView) findViewById(R.id.tvLattitude);
tvLongitude = (TextView) findViewById(R.id.tvLongitude);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locListenD = new DispLocListener();
lm.requestLocationUpdates("gps", 30000L, 10.0f, locListenD);
}
private LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateNearestLocation(location);
}
private boolean updateNearestLocation(Location lastKnownLocation) {
String locationProvider = LocationManager.NETWORK_PROVIDER;
LocationManager m_locationManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
try {
m_locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} catch (IllegalArgumentException iae) {
Log.i(TAG, "Could not find a location provider");
return false;
}
if (lastKnownLocation == null) {
lastKnownLocation = m_locationManager
.getLastKnownLocation(locationProvider);
} else {
m_locationManager.removeUpdates(locationListener);
}
if (lastKnownLocation != null) {
lastKnownLocation.getLatitude();
lastKnownLocation.getLongitude();
}
}
Perhaps you need to turn on the locations in your phone's settings:
Settings --> Location and Security --> My Location
Also if you are using an emulator keep in mind it won't generate location data unless you do it manually through the DDMS.

Sending location to emulator

I am testing the option to send coordinates to the Android Emulator using the Built in Eclipse tool.But it doesn't seem to receive them.I have this simple code:
public class Main extends MapActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView view = (MapView) findViewById(R.id.themap);
view.setBuiltInZoomControls(true);
final MapController mp = view.getController();
LocationManager manager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener listener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onLocationChanged(final Location location) {
// TODO Auto-generated method stub
mp.setCenter(new GeoPoint((int)location.getLatitude(), (int)location.getLongitude()));
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, listener);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
I have the permissions for ACCESS_FINE_LOCATION and INTERNET in the Manifest.
If someone has any explanation I would be grateful.
Did you add
<uses-library android:name="com.google.android.maps" />
to the application tag in the manifest?
You also need a MD5 Fingerprint of the SDK Debug Certificate from Google to receive Google Maps data. You can get it here.
Try to put a breakpoint inside the onLocationChanged method and see if it stops when sending the location command to the emulator. this should also work when you don't have a certificate yet.
This works for me.
Listener implementation...
public class MyLocationListener implements LocationListener {
public static final String TAG = "MyLocationListener";
private Context context;
public MyLocationListener(Context c) {
this.context = c;
}
public void onLocationChanged(android.location.Location location) {
Log.d(TAG,"LocationChanged: Lat: "+location.getLatitude()+" Lng: "+location.getLongitude());
}
}
Usage...
MyLocationListener locationListener = new MyLocationListener(this);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Register the listener with the Location Manager to receive location updates
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListener);

Android Location in background

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.

Categories

Resources