Android - RemoveUpdates not removing listener - android

I've been trying to remove location updates from my location manager however the GPS symbol continuously shows even after removeupdates has been called. I've ensured the correct listener variable name has been passed and the code is executed for the listener update. I only want to find the user's location once.
Thanks
public class MapActivity extends FragmentActivity implements OnInfoWindowClickListener, OnCameraChangeListener {
Map<Marker, Integer> markers = new HashMap<Marker, Integer>();
VenueManager venueManager;
GoogleMap map;
long last_map_refresh = 0;
Button search_btn;
CameraPosition previous_position = null;
private LocationManager locationManager;
private static final long MIN_TIME = 400;
private static final float MIN_DISTANCE = 1000;
private ProgressDialog loading;
private Button add_venue;
SharedPreferences sharedPreferences;
private LatLng user_position = null;
private NetworkManager network_manager;
private Boolean first_map_render = false;
private LocationListener location_listener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if( !locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER) ) {
AlertDialog.Builder builder = new AlertDialog.Builder(MapActivity.this);
builder.setTitle("GPS not enabled"); // GPS not found
builder.setMessage("This application requires you to enable GPS location settings. We recommend that you enable 'Use wireless networks' and 'Use GPS satellites'. Would you like to enable this setting now?"); // Want to enable?
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
finish();
MapActivity.this.startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
Intent home_intent = new Intent(MapActivity.this, HomeActivity.class);
startActivity(home_intent);
Toast.makeText(MapActivity.this, "You will not be able to use the map features of this application until you enable gps settings", Toast.LENGTH_LONG).show();
finish();
}
});
builder.create().show();
return;
}
else
{
network_manager = new NetworkManager();
location_listener = new LocationListener() {
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 16);
map.animateCamera(cameraUpdate);
draw_map(new CameraPosition.Builder().target(new LatLng(location.getLatitude(), location.getLongitude())).build());
user_position = latLng;
locationManager.removeUpdates(location_listener);
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, location_listener);
}
}

First of all when using LocationManager.NETWORK_PROVIDER you should not see the GPS symbol at all.
I see you are using Google Maps Android API v2, so my guess is outside of the code you put here you have
map.setMyLocationEnabled(true);
which shows blue dot and continuously updates it while showing Activity with MapFragment/MapView.

Related

Get location updates after GPS enabled by user

I have a simple App which currently simply asks for necessary permissions and in case GPS is OFF, you get an AlertDialog asking you if you want to switch it ON. After accepting, being taken to GPS options, enabling it, and going back to my App, I'd like to update location and here I get lost.
In other words, I'm trying to do what's stated here: https://stackoverflow.com/a/43396965/7060082
Unfortunately I can't manage to get it done and the example is a bit complicated for me to understand. Here is a piece of my code showing the relevant bits:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
private void getLatLon() {
//manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = manager.getBestProvider(criteria, false);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
manager.getLastKnownLocation(provider);
if (location != null) {
Toast.makeText(this, "This is my location: " + location.getLongitude() + ", " + location.getLatitude(), Toast.LENGTH_SHORT).show();
} else {
// manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
//location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
/*
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
*/
}
}
}
#Override
public void onLocationChanged(Location l) {
location = l;
double longitude = location.getLongitude();
double latitude = location.getLatitude();
Toast.makeText(this, "This is my location: " + longitude + ", " + latitude, Toast.LENGTH_SHORT).show();
}
After asking for ACCESS_FINE_LOCATION permission (which is also stated on the manifest) I call checkGPS(). As said before, let's you enable or not the GPS. If enabled, I call getLatLon(). If there is a lastKnownLocation, good, if not...
Here I get lost. I call requestLocationUpdates and then do nothing waiting for onLocationChanged to recieve a location update and execute the rest of the code. Am I doing it right? The result is me clicking the button, switching GPS on. Click on the button again and nothing happens.
Any help with this will help.
Many thanks for your time.
I've developed fused location api demo application and utility pack here.
General Utilities
Try it if useful for you. To get location using fused location api, you just have to write following snippet...
new LocationHandler(this)
.setLocationListener(new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// Get the best known location
}
}).start();
And if you want to customise it, simply find documentation here...
https://github.com/abhishek-tm/general-utilities-android/wiki/Location-Handler
I've written a sample code according to your need, this will handle GPS enable/disable dialog internally, try this one...
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import in.teramatrix.utilities.service.LocationHandler;
import in.teramatrix.utilities.util.MapUtils;
/**
* Lets see how to use utilities module by implementing location listener.
*
* #author Khan
*/
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, LocationListener {
private GoogleMap map;
private Marker marker;
private LocationHandler locationHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Obtaining an instance of map
FragmentManager manager = getSupportFragmentManager();
SupportMapFragment mapFragment = (SupportMapFragment) manager.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
this.locationHandler = new LocationHandler(this)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(5000)
.setFastestInterval(10000)
.setLocationListener(this);
}
#Override
public void onMapReady(GoogleMap map) {
this.map = map;
this.locationHandler.start();
}
#Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
if (marker == null) {
marker = MapUtils.addMarker(map, latLng, R.drawable.ic_current_location);
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 14), 500, null);
} else {
marker.setPosition(latLng);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (locationHandler != null) {
locationHandler.stop();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == LocationHandler.REQUEST_LOCATION) {
locationHandler.start();
}
}
}
Hope it will help you.
Your current code doesn't wait for the user to make a choice before calling getLatLon() in the case where GPS is disabled.
You will need to add a onActivityResult() override that will be called when the user goes back to your app.
First, remove the call to getLatLon() in the checkGPS() method for the case where GPS is disabled:
private void checkGPS() {
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.GPS_error)
.setCancelable(false)
.setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
public void onClick(#SuppressWarnings("unused") final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
Intent gps = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(gps, 1);
//Remove this:
//getLatLon();
}
})
.setNegativeButton(R.string.deny, new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, #SuppressWarnings("unused") final int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
getLatLon();
}
}
Then, add the onActivityResult() override, check the setting again, and if it's now enabled then call getLatLon():
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
getLatLon();
}
}
after some time busy with other projects, got back to this one and I removed the getLatLon(); function from the checkGPS(); function and that's it, code is fine. I was using the emulator to check if this was working, but I forgot that the emulator has a fixed value for the latitude and longitude, so you get no updates like a real mobile phone, and thus it looked as if it was not working properly.
Sort of a newby mistake. Regardless, thanks for your offers. Was interesting looking at different ways of doing the same thing.
Sartox

How to get the current location of the device? google maps

I need to know the latitude and longitude of the marker that is placed when I click on my map, and I also need to know how to implement so that when I open the map a marker is placed in the current location, I have seen many videos and tutorials but none works or It's obsolete etc
the relevant code:
onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
mPost = new Post();
initPantallaAdd();
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());
if(status == ConnectionResult.SUCCESS){
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.mapAddUbicacion);
mapFragment.getMapAsync(this);
}else{
Toast.makeText(getApplicationContext(), "Please install google play services", Toast.LENGTH_SHORT).show();
}
}
onMapReady:
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
UiSettings uiSettings = mMap.getUiSettings();
uiSettings.setZoomControlsEnabled(true);
LatLng sydney = new LatLng(-0.193805, -78.467102);
CameraPosition cp = CameraPosition.builder().target(sydney).zoom(16).tilt(3).build();
float zoomlevel = 16;
mMap.moveCamera(CameraUpdateFactory.newCameraPosition(cp));
mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
mMap.clear();
MarkerOptions markerOptions = new MarkerOptions().position(new LatLng(latLng.latitude, latLng.longitude)).title("Selected point");
mMap.addMarker(markerOptions);
}
});
}
I implemented these methods but I don't know what to do:
//==============================================================================================
// ON CONNECTION CALLBACKS
#Override
public void onConnected(#Nullable Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
//==============================================================================================
// LOCATION LISTENER
#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) {
}
To work with map you have to follow some steps to configure it.
1- create a project at google developer console. https://console.developers.google.com/
2- select the project and leftmenu will show credential option click on it and than you will get option create credentialclick on it than it will ask for create api key click and create our project api key.
3-click on dashboard and select the project on top of the screen here you will get an option for enable api.
4- In this you will there is many google api, in the google map api section select google map api android and click enable .
now you will get a working api key this api key is used to work with map here i am giving you my repository you can take example from it. you do not need to configure for api key i am using my api key in it.
If you want to use you own api key than only you need to do is update the api key in the project inside manifiest file meta data tag. here is a working example
GPS service is needed to get current location latitude and longitude.
Android Location API will provide the fused location functionality to you. Check the following links for better understanding.
http://www.vogella.com/tutorials/AndroidLocationAPI/article.html
http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/
Check out this code for getting the current latitude and longitude...
public class MerchantTrack extends Common implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener {
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.merchant_track);
backbuttn=(ImageView)findViewById(R.id.backbuttn);
getSupportActionBar().hide();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this).build();
connectClient();
}
protected void connectClient() {
// Connect the client.
if (isGooglePlayServicesAvailable() && mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
private boolean isGooglePlayServicesAvailable() {
// Check that Google Play services is available
int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
// If Google Play services is available
if (ConnectionResult.SUCCESS == resultCode) {
// In debug mode, log the status
Log.d("Location Updates", "Google Play services is available.");
return true;
} else {
// Get the error dialog from Google Play services
Dialog errorDialog = GooglePlayServicesUtil.getErrorDialog(resultCode, this,
CONNECTION_FAILURE_RESOLUTION_REQUEST);
// If Google Play services can provide an error dialog
if (errorDialog != null) {
// Create a new DialogFragment for the error dialog
UberMapsActivity.ErrorDialogFragment errorFragment = new UberMapsActivity.ErrorDialogFragment();
errorFragment.setDialog(errorDialog);
errorFragment.show(getSupportFragmentManager(), "Location Updates");
}
return false;
}
}
#Override
public void onConnected(Bundle bundle) {
Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (location != null) {
//Toast.makeText(this, "GPS location was found!", Toast.LENGTH_SHORT).show();
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
latitudE = location.getLatitude();
longitudE = location.getLongitude();
Log.d("locationnss", String.valueOf(latitudE));
new MerchLocAsync().execute();
} else {
new AlertDialog.Builder(MerchantTrack.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setMessage("Current location is unavailable!")
.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.show();
}
startLocationUpdates();
}
protected void startLocationUpdates() {
mLocationRequest = new LocationRequest();
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onBackPressed() {
Intent home = new Intent(MerchantTrack.this,Home.class);
startActivity(home);
super.onBackPressed();
}

Location Listener Can't Reach Location

My app uses users location and have fragments. In main activity this fragments changes.
But there is a problem here. I implement "Location Listener" interface to my fragment class, and drop the breakpoint in "onLocationChanged" event. And program never hit the breakpoint.
Why I can not reach the users location?
Here is my code:
public class NearestCoffeeVenueFragment extends Fragment implements LocationListener{
// GPS Variables
private LocationManager locationManager;
private Location lastLocation;
private String provider;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
locationManager = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,this);
provider = LocationManager.NETWORK_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(location != null){
lastLocation = location;
Toast.makeText(getActivity(), getString(R.string.gps_success), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getActivity(),getString(R.string.gps_fail),Toast.LENGTH_SHORT).show();
cannotReachGpsWarning();
}
return inflater.inflate(R.layout.fragment_nearest_coffee_venue, container, false);
}
/** LocationListener Interface Functions
* */
#Override
public void onLocationChanged(Location location){
Toast.makeText(getActivity(),"Long: "+location.getLongitude()+" Lat:"+location.getLatitude(),Toast.LENGTH_LONG).show();
lastLocation = location;
}
#Override
public void onStatusChanged(String provider,int status,Bundle extras){
}
#Override
public void onProviderEnabled(String provider){
Toast.makeText(getActivity(),getString(R.string.gps_enabled_provider)+provider,Toast.LENGTH_LONG).show();
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText(getActivity(),getString(R.string.gps_disabled_provider)+provider,Toast.LENGTH_LONG).show();
}
/// warning messages and buttons setted from strings file.
private void cannotReachGpsWarning(){
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getString(R.string.gps_disabled))
.setCancelable(false)
.setPositiveButton(getString(R.string.gps_enable),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
showGPSOptions();
}
});
builder.setNegativeButton(getString(R.string.gps_disable),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void showGPSOptions(){
Intent gpsOptionsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(gpsOptionsIntent);
}
As I say, I don't see any toasts or anything else. The fragment's doesn't hit the breakpoint on "onLocationChanged" function. This means fragment can't reach location. And when fragment starts, I see "Can not reach location" error even the phone's location was on.
Did you enable location in the device for both sources GPS ans NETWORK? Currently in your code your'e asking for network provider, if this provider is disabled the method getLastKnownLocation will return null.

Google map v2 marker position

In one of my activities of an app i'm creating, I want the user to be able to click a button and once clicked a marker will be placed at the current position.
setMarker.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Creating a LatLng object for the current location
LatLng latLng = new LatLng(location.getLatitude(),
location.getLongitude());
googleMap.addMarker(new MarkerOptions()
.position(LatLng)
.title("Hello world"));
I am sending you some codes. Read them and use them appropriately. On your button click
private void locateMe() {
// Checking for GPS Enabled
locationManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
if (!isGPSEnabled) {
// GPS is disabled
askUserToEnableGPS();
}
}
/**
*
*/
private void askUserToEnableGPS() {
// Asking user to enable GPS
// 1. Instantiate an AlertDialog.Builder with its constructor
AlertDialog.Builder builder = new AlertDialog.Builder(this);
// 2. Chain together various setter methods to set the dialog
// characteristics
builder.setMessage(R.string.generic_gps_not_found)
.setTitle(R.string.generic_gps_not_found_message_title)
.setPositiveButton(R.string.generic_yes,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected yes
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
})
.setNegativeButton(R.string.generic_no,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User selected no
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.create();
dialog.show();
}
LocationListener listener = new LocationListener() {
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location arg0) {
// Setting the marker
if (googleMap == null || location == null) {
return;
} else {
googleMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(
location.getLatitude(), location.getLongitude())));
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
// Do something after 3000ms
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
}, 1000);
Marker myLocation = googleMap.addMarker(new MarkerOptions()
.position(
new LatLng(location.getLatitude(), location
.getLongitude()))
.title("Me")
.snippet("I am here")
.icon(BitmapDescriptorFactory
.fromResource(R.drawable.ic_launcher)));
}
locationManager.removeUpdates(listener);
locationManager = null;
}
};
Declare a global boolean like boolean putMarkerByButtonClick = false ; and try this
setMarker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
putMarkerByButtonClick = true ;
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 400, 1000, this);
}
});
and on your override method onLocationChange method write this :
#Override
public void onLocationChanged(Location location) {
if(putMarkerByButtonClick ){
putMarkerByButtonClick = false ;
map.addMarker(new MarkerOptions()
.position(new LatLng(location.getLatitude(), location.getLongitude()))
.title("Hello world"));
}
}

gps doesnt turn off on app exit

the method startSightManagement() is called twice throug my program, so i have two location Manager objects.
private void startSightManagement() {
String locationService = Context.LOCATION_SERVICE;
locationManager = (LocationManager)getSystemService(locationService);
// Get the GPS provider and request location updates
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
provider = locationManager.getBestProvider(criteria, true);
locationManager.requestLocationUpdates(provider, 2000, 2, this);
// Obtain last known location and update the UI accordingly
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
sightManager = new SightManager(this);
// Set up the first sight
setSight();
}
my onPause() Activity with removeUpdates(this)-->This only removes one instance, how do i remove the other one??
protected void onPause() {
myLocationOverlay.disableMyLocation();
locationManager.removeUpdates(this);
locationManager=null;
// TODO Auto-generated method stub
super.onPause();
//Shutdown TTS everytime when activity is paused(Tolga)
if (mTts != null) {
mTts.stop();
}
// Unregister the proximity intent receiver. This also prevents the app from
// leaking when it is closed.
if (proximityIntentReceiver!=null) {
unregisterReceiver(proximityIntentReceiver);
}
}
Second problem is: app crashes when gps isnt enabled on start and i click yes when asked if gps should be enabled. when i remove these two lines everything works fine:
locationManager.removeUpdates(this);
locationManager=null;
here is the buildAlert method if gps isnt enabled on start:
private void buildAlertMessageNoGps() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("GPS ist deaktiviert. Standorteinstellungen anzeigen?")
.setCancelable(false)
.setPositiveButton("Ja", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
startActivityForResult(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS), ENABLE_GPS_SUB);
}
})
.setNegativeButton("Nein", new DialogInterface.OnClickListener() {
public void onClick(final DialogInterface dialog, final int id) {
dialog.cancel();
finish();
}
});
final AlertDialog alert = builder.create();
alert.show();
}

Categories

Resources