I have an app that updating user location is the main feature of it.
So far I have a class that get users location through both GPS and NETWORK providers . It works just fine :
public class UserLocation {
private String TAG = "UserLocation";
Timer timer;
LocationManager locationManager;
OnLocationResultListener listener;
boolean gps_enabled = false;
boolean network_enabled = false;
public UserLocation setListener(OnLocationResultListener listener) {
this.listener = listener;
return this;
}
public boolean getLocation() {
if (locationManager == null) {
locationManager = (LocationManager) G.context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location GPS_PROVIDER is off");
ex.printStackTrace();
}
try {
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
Log.e(TAG, "Location NETWORK_PROVIDER is off");
ex.printStackTrace();
}
timer = new Timer();
timer.schedule(new GetLastLocation(), 0, GlobalConsts.LOCATION_RECHECK_TIME);
return true;
}
LocationListener gpslocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling gpslocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener networklocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Log.e(TAG, "Calling networklocationListener==> onLocationChanged");
timer.cancel();
listener.onGotLocation(location);
locationManager.removeUpdates(networklocationListener);
locationManager.removeUpdates(gpslocationListener);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
class GetLastLocation extends TimerTask {
#Override
public void run() {
Log.e(TAG, "Getting last location in TimeTask ");
locationManager.removeUpdates(gpslocationListener);
locationManager.removeUpdates(networklocationListener);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
listener.onGotLocation(gps_loc);
else
listener.onGotLocation(net_loc);
return;
}
if (gps_loc != null) {
listener.onGotLocation(gps_loc);
return;
}
if (net_loc != null) {
listener.onGotLocation(net_loc);
return;
}
if (gps_loc == null && net_loc == null) {
Log.e(TAG, "tried to get location in Timetask but both location was null");
} else if (gps_loc == null) {
Log.e(TAG, "gps_loc is null in time task");
} else {
Log.e(TAG, "net_loc is null in time task");
}
listener.onGotLocation(null);
}
}
public interface OnLocationResultListener {
void onGotLocation(Location location);
void onNoLocationProvider();
}
}
The thing that I want is to get user location even if he is not using the app ( I mean getting his location when it changes , even if the app is not up and running)
What is the best approach to achieve this ?
Should I make a service and run this ?
How about using Google Play Location Api ? Does this help me ?
Thanks in advance.
Create this service which will always running in background even if your application is not running.
public class MyLocationService extends Service implements LocationListener,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
public MyLocationService() {
}
#Override
public void onCreate() {
super.onCreate();
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(LocationServices.API).
addConnectionCallbacks(this).
addOnConnectionFailedListener(this)
.build();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mGoogleApiClient.connect();
Toast.makeText(this, "Location services started", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
#Override
public void onLocationChanged(Location location) {
System.out.println("MyLocationService.onLocationChanged");
// do your work here with location
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = LocationRequest.create();
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setInterval(1000); // Update location every second
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
#Override
public void onDestroy() {
Toast.makeText(this, "Location services stopped", Toast.LENGTH_LONG).show();
Location loc = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mGoogleApiClient.disconnect();
super.onDestroy();
}
}
Related
I have implemented to get the user's current location when user clicked the agreement button. I have implemented the LocationListener in the activity and I have unregistered the listener at both onStop and onDestroyed. But according to LeakCanary, memory leak is still existing.
This is a brief of My code.
public class UserProfileEditActivity extends BaseActivity implements DatePickerDialog.OnDateSetListener, LocationListener, LocationResult {
LocationManager locationManager;
LocationHelper myLocation;
LocationResult locationResult;
public void getCurrentUserLocation() {
myLocation.getLocation(this);
}
#Override
protected void onStart() {
super.onStart();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
myLocation = new LocationHelper(locationManager, this);
}
#Override
protected void onPause() {
locationManager.removeUpdates(this);
super.onPause();
}
#Override
protected void onStop() {
reset();
super.onStop();
}
#Override
protected void onDestroy() {
reset();
super.onDestroy();
}
//implementation of LocationResult
#Override
public void gotLocation(Location location) {
//Got the location!
getCurrentUserHomeTown(location);
if (location != null)
showLog("Location lat :" + location.getLatitude() + " long :" + location.getLongitude());
}
private void reset() {
if (confirmationDialog != null)
confirmationDialog.dismiss();
if (myLocation != null) {
myLocation.stopLocationListeners();
locationManager.removeUpdates(this);
locationResult = null;
locationManager = null;
myLocation = null;
}
}
#Override
public void onLocationChanged(Location location) {
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
And this is how I trigger to gather location.
public void getCurrentUserLocation() {
myLocation.getLocation(this);
}
this is LocationHelper.class
public class LocationHelper {
private LocationResult locationResult;
private LocationManager locationManager;
private boolean gps_enabled = false;
private boolean network_enabled = false;
// private Timer timer;
private LocationListener locationListener;
public LocationHelper(LocationManager locationManager, LocationListener locationListener) {
this.locationManager = locationManager;
this.locationListener = locationListener;
}
#SuppressLint("MissingPermission")
public boolean getLocation(LocationResult result) {
//I use LocationResult callback class to pass location value from MyLocation to user code.
locationResult = result;
//exceptions will be thrown if provider is not permitted.
try {
gps_enabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
network_enabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ignored) {
}
//don't start listeners if no provider is enabled
if (!gps_enabled && !network_enabled)
return false;
if (gps_enabled)
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, (float) 10.0, locationListener);
if (network_enabled)
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10 * 1000, (float) 10.0, locationListener);
getLastLocation();
// timer.schedule(new GetLastLocation(locationManager, locationListenerGps, locationListenerNetwork, gps_enabled, network_enabled, locationResult), 40000);
return true;
}
#SuppressLint("MissingPermission")
public void getLastLocation() {
locationManager.removeUpdates(locationListener);
Location net_loc = null, gps_loc = null;
if (gps_enabled)
gps_loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (network_enabled)
net_loc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
//if there are both values use the latest one
if (gps_loc != null && net_loc != null) {
if (gps_loc.getTime() > net_loc.getTime())
locationResult.gotLocation(gps_loc);
else
locationResult.gotLocation(net_loc);
return;
}
if (gps_loc != null) {
locationResult.gotLocation(gps_loc);
return;
}
if (net_loc != null) {
locationResult.gotLocation(net_loc);
return;
}
locationResult.gotLocation(null);
}
public void stopLocationListeners() {
locationManager.removeUpdates(locationListener);
// if (timer != null) {
// timer.cancel();
// timer = null;
// }
locationListener = null;
locationResult = null;
locationManager = null;
}
}
But the LeakCanary keep indicating there is memory leak with LocationManager and LocationListener. Please Help me find out this.
In my application's splash screen, I'm starting to listen the location via gps or network until my second activity opens.
my network location listener:
private LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
newLocationReceived(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
my gps location listener:
private LocationListener locationListenerGPS = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
newLocationReceived(location);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
Inside onCreate I call getLocation method, for permissions I use rxPermission:
#SuppressLint("MissingPermission")
private void getLocation() {
rxPermissions
.request(Manifest.permission.ACCESS_FINE_LOCATION)
.subscribe(granted -> {
if (granted) {
boolean gpsEnabled, networkEnabled;
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (locationManager != null) {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (gpsEnabled && locationListenerGPS != null) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0L, 0f, locationListenerGPS);
}
if (networkEnabled && locationListenerNetwork != null) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0L, 0f, locationListenerNetwork);
}
}
} else {
Timber.e("LOCATION PERMISSION DENIED");
}
});
}
When new location is received I call:
private void newLocationReceived(Location location) {
if (locationManager != null) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.removeUpdates(locationListenerGPS);
}
locationManager = null;
this.location = location;
}
And in order to avoid memory leaks I call this method in onPause, onStop and onDestroy:
private void stopLocationListener() {
if (locationManager != null) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.removeUpdates(locationListenerGPS);
locationManager = null;
}
if (locationListenerNetwork != null) locationListenerNetwork = null;
if (locationListenerGPS != null) locationListenerGPS = null;
}
However, In order to LeakCanary I still get memory leaks in location manager. How can I resolve this? Also sometimes My splash screen passes the progresses too fast and my runtime permission can stay at background too
In my android app I'm retrieving user location for every 3 minutes and somehow I'm doing it in the following way.problems so far I have faced are
Whenever I'm getting location updates I'm getting multiple values at same time
Sometimes I'm getting both GPS and NETWORK provider values at a time.
I need only one value and also it should be either GPS or NETWORK Provider value,How to achieve this.
Here is my Service
public class MyService extends Service {
private static final String TAG = "TESTGPS";
private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 180000;
private static final float LOCATION_DISTANCE = 0.0f;
double lati,longi;
String loc_name;
private class LocationListener implements android.location.LocationListener {
Location mLastLocation;
public LocationListener(String provider) {
Log.i(TAG, "LocationListener " + provider);
mLastLocation = new Location(provider);
}
#Override
public void onLocationChanged(Location location) {
Log.i(TAG, "onLocationChanged: " + location);
Toast.makeText(getApplicationContext(), ""+location.getLatitude()+"==>"+location.getLongitude(), Toast.LENGTH_SHORT).show();
lati = location.getLatitude();
longi = location.getLongitude();
Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
try {
List<Address> addressList = geocoder.getFromLocation(
lati, longi, 1);
if (addressList != null && addressList.size() > 0) {
{
loc_name = addressList.get(0).getAddressLine(1);
}
AsyncHttpClient client = new AsyncHttpClient();
final RequestParams params = new RequestParams();
params.put("sendingJSON", composeLocation());
Toast.makeText(getApplicationContext(), "" + params, Toast.LENGTH_LONG).show();
client.post("http://192.168.0.120/gpstracker/send_location.php", params, new AsyncHttpResponseHandler() {
public void onSuccess(String response) {
Log.i("Status ==> ", "Sent to server");
}
public void onFailure(int statusCode, Throwable error, String content) {
if (statusCode == 404) {
Toast.makeText(getApplicationContext(), "Requested resource not found", Toast.LENGTH_LONG).show();
} else if (statusCode == 500) {
Toast.makeText(getApplicationContext(), "Something went wrong at server end", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Unexpected Error occcured! [Most common Error: Device might not be connected to Internet]", Toast.LENGTH_LONG).show();
}
}
});
}
} catch (IOException e) {
e.printStackTrace();
mLastLocation.set(location);
}
}
#Override
public void onProviderDisabled(String provider) {
Log.i(TAG, "onProviderDisabled: " + provider);
}
#Override
public void onProviderEnabled(String provider) {
Log.i(TAG, "onProviderEnabled: " + provider);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.i(TAG, "onStatusChanged: " + provider);
}
}
LocationListener[] mLocationListeners = new LocationListener[]{
new LocationListener(LocationManager.GPS_PROVIDER),
new LocationListener(LocationManager.NETWORK_PROVIDER)
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(MyService.this, "Service Started", Toast.LENGTH_SHORT).show();
Log.i("Service Started", "Started");
return START_STICKY;
}
#Override
public void onCreate() {
Log.e(TAG, "onCreate");
initializeLocationManager();
try {
mLocationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[1]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "network provider does not exist, " + ex.getMessage());
}
try {
mLocationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
mLocationListeners[0]);
} catch (java.lang.SecurityException ex) {
Log.i(TAG, "fail to request location update, ignore", ex);
} catch (IllegalArgumentException ex) {
Log.d(TAG, "gps provider does not exist " + ex.getMessage());
}
}
#Override
public void onDestroy() {
Log.e(TAG, "onDestroy");
super.onDestroy();
if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) {
try {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
mLocationManager.removeUpdates(mLocationListeners[i]);
} catch (Exception ex) {
Log.i(TAG, "fail to remove location listners, ignore", ex);
}
}
}
}
private void initializeLocationManager() {
Log.i(TAG, "initializeLocationManager");
if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
}
}
public String composeLocation()
{
ArrayList<HashMap<String, String>> locationList = new ArrayList();
HashMap<String, String> map = new HashMap();
String parsed_lati = String.valueOf(lati);
String parsed_longi = String.valueOf(longi);
map.put("e1", "123");
map.put("lati",parsed_lati);
map.put("longi",parsed_longi);
map.put("loc_name",loc_name);
locationList.add(map);
return new GsonBuilder().create().toJson(locationList);
}
}
You should first check before getting location from both. First check if location is available through gps and if not then use network to get location.
Here is a sample class which have methods for checking location.
public class GPSTracker extends Service implements LocationListener {
private final Context context;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
public boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.context = context;
getLocation();
}
public Location getLocation() {
try {
locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(!isGPSEnabled && !isNetworkEnabled) {
} else {
this.canGetLocation = true;
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();
}
}
}
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();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
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 showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("Turn on your GPS to find nearby helpers");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#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
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
You should use Criteria to request location update instead of using Provider:
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
locationManager.requestSingleUpdate(criteria, listener, null);
That way you can use only one listener and the location value can be from either GPS or NETWORK provider.
I have the following class to get the user location.
public class GetUserLocation extends Activity {
Timer timer1;
LocationManager locationManager = null;
LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public static Location userLocation = null;
public String checkProviders(Context context) {
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
gpsEnabled = false;
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
networkEnabled = false;
}
if(!gpsEnabled && !networkEnabled)
return "No Location Service Found.\nPlease turn on your location service by\nenabling GPS or Data Service or WI-FI";
if(gpsEnabled && !networkEnabled)
return "No Internet Service Found.\nPlease turn on your inernet service by\nenabling Data Service or WI-FI";
return null;
}
public boolean getLocation(Context context, LocationResult result) {
locationResult = result;
if (locationManager == null) {
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
// exceptions will be thrown if provider is not permitted.
try {
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {
}
try {
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {
ex.printStackTrace();
}
// don't start listeners if no provider is enabled
if (!gpsEnabled && !networkEnabled)
return false;
if (gpsEnabled) {
locationManager.removeUpdates(locationListenerGps);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,locationListenerGps);
}
if (networkEnabled) {
locationManager.removeUpdates(locationListenerNetwork);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0,locationListenerNetwork);
}
timer1 = new Timer();
//timer1.schedule(new GetLastLocation(), 30000);
return true;
}
LocationListener locationListenerGps = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
LocationListener locationListenerNetwork = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
timer1.cancel();
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
// class GetLastLocation extends TimerTask {
// #Override
// public void run() {
//
// locationManager.removeUpdates(locationListenerGps);
// locationManager.removeUpdates(locationListenerNetwork);
//
// Location networkLocation = null, gpsLocation = null;
// if (gpsEnabled) {
// //t = Calendar.getInstance().getTimeInMillis();
// gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// }
//
// if (networkEnabled) {
// networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
// }
//
// // if there are both values use the latest one
// if (gpsLocation != null && networkLocation != null) {
//
// if (gpsLocation.getTime() > networkLocation.getTime())
// locationResult.gotLocation(gpsLocation);
// else
// locationResult.gotLocation(networkLocation);
//
// return;
// }
//
// if (gpsLocation != null) {
// locationResult.gotLocation(gpsLocation);
// return;
// }
//
// if (networkLocation != null) {
// locationResult.gotLocation(networkLocation);
// return;
// }
//
// locationResult.gotLocation(null);
// }
// }
public static abstract class LocationResult {
public abstract void gotLocation(Location location);
}
public void removeUpdates() {
if(timer1!=null) {
timer1.cancel();
}
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
userLocation = null;
locationResult.gotLocation(null);
}
public Timer getTimer() {
return this.timer1;
}
}
This code is working good for other devices, but not in galaxy s3. But in the test S3 device the google map is getting the user location fix.
Can anyone say why is this happening? Any Hints will be appreciated.
I solved a problem like this, installing the APP GPS Status, that reset the GPS.
Solution found at:
http://productforums.google.com/forum/#!topic/maps/q24Cq4sQAtc%5B1-25-false%5D
OR just, try clearing the App Data from "Maps".
You'll then need to re-grant access to location services when prompted.
Hugs
I have an app that finds the users location (loading in a progress dialog) using GPS or network signal , when it finds it's location, the coordinates are written in a text view . If the GPS doesn't find a location in 40 sec or the user clicks on the cancel button , then the dialog closes. The problem is that if I click to cancel the dialog , it doesn't dismiss. However, if I click again, it dismisses. Why do I have to click twice ?!? Below is the source code:
public class MainActivity extends Activity {
private LocationControl locationControlTask;
private boolean hasLocation = false;
LocationHelper locHelper;
protected Location currentLocation;
private TextView myText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myText = (TextView)findViewById(R.id.mytext);
locHelper = new LocationHelper();
locHelper.getLocation(MainActivity.this, locationResult);
locationControlTask = new LocationControl();
locationControlTask.execute(this);
}
protected void onStart()
{
super.onStart();
// ....
new LocationControl().execute(this);
}
private class LocationControl extends AsyncTask<Context, Void, Void>
{
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute()
{
this.dialog.setMessage("Tap to cancel");
this.dialog.setTitle("Searching");
this.dialog.setCancelable(true);
this.dialog.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(which == Dialog.BUTTON_NEGATIVE) {
dialog.dismiss();
Toast.makeText(MainActivity.this, "dialog canceled", Toast.LENGTH_SHORT).show();
}
}
});
this.dialog.show();
}
protected Void doInBackground(Context... params)
{
//Wait 40 seconds to see if we can get a location from either network or GPS, otherwise stop
Long t = Calendar.getInstance().getTimeInMillis();
while (!hasLocation && Calendar.getInstance().getTimeInMillis() - t < 40000) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
};
return null;
}
protected void onPostExecute(final Void unused)
{
if(this.dialog.isShowing())
{
this.dialog.dismiss();
}
if (currentLocation != null)
{
//useLocation();
String text = "lat:"+currentLocation.getLatitude()+" long:"+currentLocation.getLongitude();
myText.setText(text);
}
else
{
Toast.makeText(MainActivity.this, "location could not be found", Toast.LENGTH_SHORT).show();
//Couldn't find location, do something like show an alert dialog
}
}
}
public LocationResult locationResult = new LocationResult()
{
#Override
public void gotLocation(final Location location)
{
currentLocation = new Location(location);
hasLocation = true;
}
};
#Override
protected void onStop() {
locHelper.stopLocationUpdates();
locationControlTask.cancel(true);
super.onStop();
}
}
The location helper:
public class LocationHelper
{
LocationManager locationManager;
private LocationResult locationResult;
boolean gpsEnabled = false;
boolean networkEnabled = false;
public boolean getLocation(Context context, LocationResult result)
{
locationResult = result;
if(locationManager == null)
{
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
}
//exceptions thrown if provider not enabled
try
{
gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
catch (Exception ex) {}
try
{
networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
catch (Exception ex) {}
//dont start listeners if no provider is enabled
if(!gpsEnabled && !networkEnabled)
{
return false;
}
if(gpsEnabled)
{
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListenerGps);
}
if(networkEnabled)
{
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListenerNetwork);
}
//GetLastLocation();
return true;
}
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerNetwork);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location)
{
locationResult.gotLocation(location);
locationManager.removeUpdates(this);
locationManager.removeUpdates(locationListenerGps);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extra) {}
};
private void GetLastLocation()
{
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
Location gpsLocation = null;
Location networkLocation = null;
if(gpsEnabled)
{ //if()
gpsLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
if(networkEnabled)
{
networkLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
//if there are both values use the latest one
if(gpsLocation != null && networkLocation != null)
{
if(gpsLocation.getTime() > networkLocation.getTime())
{
locationResult.gotLocation(gpsLocation);
}
else
{
locationResult.gotLocation(networkLocation);
}
return;
}
if(gpsLocation != null)
{
locationResult.gotLocation(gpsLocation);
return;
}
if(networkLocation != null)
{
locationResult.gotLocation(networkLocation);
return;
}
//locationResult.gotLocation(null);
}
public void stopLocationUpdates() {
locationManager.removeUpdates(locationListenerGps);
locationManager.removeUpdates(locationListenerNetwork);
}
public static abstract class LocationResult
{
public abstract void gotLocation(Location location);
}
}
the xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/mytext"
android:textSize="15dip"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Main activity"/>
</LinearLayout>
and these 2 permissions in manifest
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I would appreciate it if anyone would take a look at the bug.
I didn't do an in-depth analysis of your code, but you are starting the aysnc task in both onCreate and onStart. Remove it from one of those, because I suspect you simply have one dialog on top of the other.