I am developing an app that gets the user's location.
It works fine.
The issue is that I have a memory leak.
I am not exactly sure why and I think it's from the Location Services but I am not sure.
I have added Leak Canary to my app and it has shown me that I have a 74 mb leak from: android.hardware.SystemSensorManager$SensorEventQueue.mListener
Other times it is from com.edon.freiner.siddur.MainActivity$26.this$0 //that is my app
(anonymous implementation of android.locaition.LocationListener)
I am not sure where to look in my app because I commented out all my Location code to see if there was a change in the memory graph in Android Studio, I could not find any changes.
Here is my code:
public void startLocation() {
Log.d("Start Location", " Started");
LocationListener mLocationListener = new LocationListener() {
#Override
public void onLocationChanged(final Location location) {
DataVariables.getInstance().setLatitude(location.getLatitude());
DataVariables.getInstance().setLongitude(location.getLongitude());
latitude = location.getLatitude();
longitude = location.getLongitude();
Log.d("Loc Manager latitude", "`" + location.getLatitude());
Log.d("Loc Manager longitude", "`" + location.getLongitude());
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
if (mLocationManager.getAllProviders().contains(LocationManager.NETWORK_PROVIDER)) {
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000,
1000, mLocationListener);
}
}
}
Related
I have trouble getting latitude and longitude on Itel A16 device (Android 8.1.0). I have used the following code, which works fine based on my test on other devices and emulators. But not on Itel A16 I would appreciate any help to fix this so that the Toast can show device location.
LocationManager locationManager = (LocationManager) getActivity().getSystemService(getContext().LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
double MyLat = location.getLatitude();
double MyLong = location.getLongitude();
Toast.makeText(getContext(), " latitude: " + MyLat + " longitude: " + MyLong, Toast.LENGTH_LONG).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//Location test
if (checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(getContext(),Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
I fixed the issue with FusedLocationProviderClient , following Android Developers instructions
I'm trying to implement a locationListener in my app but somehow onLocationChanged always gives the location of googleplex instead of my virtual device "location"
if(location == null){
Log.i("YEH", "WE MAY HAVE A PROBLEM ");
}
Intent intent = new Intent(getApplicationContext(),MapsActivity.class);
intent.putExtra("Latitude", location.getLatitude());
intent.putExtra("Longitude",location.getLongitude());
Log.i("LatLong", "LAt: " + location.getLatitude() + "LONG" + location.getLongitude());
startActivity(intent);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
if (Build.VERSION.SDK_INT >= 23) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
} else {
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER,locationListener,null);
}
} else {
locationManager.requestSingleUpdate(LocationManager.NETWORK_PROVIDER,locationListener,null);
}
when i am trying to get current location using GPS Tracker ,it is tacking time only for first time but i want to get location after specific interval ? i am getting all address line by line like locality sub locality and all but after that interval for first time any solution will be appreciated..
Start your app service in background to get timely location updates.
public class MYService extends Service implements LocationListener {
}
and do async task on timely to get periodic location updates.
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
}
});
}
};
//Starts after 20 sec and will repeat on every 20 sec of time interval.
timer.schedule(doAsynchronousTask, 20000,20000); // 20 sec timer
it will give location updates on every 20 SEC.
Try this code.
make an interface GetLocation
public interface GetLocation {
public void onLocationChanged(Location location);
public void onStatusChanged(String s, int i, Bundle bundle);
public void onProviderEnabled(String s);
public void onProviderDisabled(String s);
}
then make a class CurrentLocation and implements LocationListener
public class CurrentLocation implements LocationListener {
Context context;
LocationManager locationManager;
String provider;
GetLocation getLocation;
public CurrentLocation(Context context) {
this.context = context;
getLocation = (GetLocation) context;
location();
}
public void location() {
// Getting LocationManager object
locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
// anruag getting last location
// Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
// Creating an empty criteria object
Criteria criteria = new Criteria();
// Getting the name of the provider that meets the criteria
provider = locationManager.getBestProvider(criteria, false);
if (provider != null && !provider.equals(" ")) {
// Get the location from the given provider
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
if (location != null)
onLocationChanged(location);
else {
}
// Toast.makeText(context, "Location can't be retrieved", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "No Provider Found", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onLocationChanged(Location location) {
// Log.e("Location", location.getProvider() + "==" + location.getAccuracy() + "==" + location.getAltitude() + "==" + location.getLatitude() + "==" + location.getLongitude());
getLocation.onLocationChanged(location);
String message = String.format(
"New Location \n Longitude: %1$s \n Latitude: %2$s",
location.getLongitude(), location.getLatitude());
ConstantValues.UPlat = String.valueOf(location.getLatitude());
ConstantValues.UPlng = String.valueOf(location.getLongitude());
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
Log.e("onStatusChanged", "==" + s);
getLocation.onStatusChanged(s, i, bundle);
}
#Override
public void onProviderEnabled(String s) {
Log.e("onProviderEnabled", "==" + s);
getLocation.onProviderEnabled(s);
}
#Override
public void onProviderDisabled(String s) {
Log.e("onProviderDisabled", "==" + s);
getLocation.onProviderDisabled(s);
// alertbox("GPS STATUS", "Your GPS is: OFF");
// Toast.makeText(context, "Please turn on the GPS to get current location.", Toast.LENGTH_SHORT).show();
try {
ConstantValues.showDialogOK("Please turn on the GPS to get current location.", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
switch (i) {
case DialogInterface.BUTTON_POSITIVE:
Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
context.startActivity(myIntent);
dialogInterface.dismiss();
break;
case DialogInterface.BUTTON_NEGATIVE:
dialogInterface.dismiss();
break;
}
}
}, context);
} catch (Exception e) {
Log.e("exception", e.toString()+"==");
}
}
}
call this class in any Activity where you want to get the current location
CurrentLocation currentLocation;
declare these two global variables for minimum distance change and time interval
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1;
// Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000;
make its object in onCreate
currentLocation = new CurrentLocation(this);
make a method
public void locationWithPermission() {
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
if (checkAndRequestPermissions()) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
return;
}
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new CurrentLocation(this));
}
}
and call this method in your Activity on any event you want to get Location
I am trying to get android location , I have this piece of code yet location is never returned. I have searched on stack overflow.
I found this bug : https://code.google.com/p/android/issues/detail?id=57707
But there is no fix till now, or i couldnt find one.
This is the code. Any help would be much appreciated
Criteria criteria = new Criteria();
criteria.setCostAllowed(true);
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
final LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = lm.getBestProvider(criteria, true);
Location l = lm.getLastKnownLocation(provider);
final String date = fmtForPresenter.print(dt);
if(l==null) {
lm.requestLocationUpdates(provider, 100, 200,
new android.location.LocationListener() {
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Log.e("PROVIDER", "PRO: " + provider);
}
#Override
public void onProviderDisabled(String provider) {
Log.e("PROVIDER", "PRO: " + provider);
}
#Override
public void onLocationChanged(final Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
presenter.getFoot(userProfile.getToken(),"public",lat,lng,date);
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
PackageManager.PERMISSION_GRANTED)) {
lm.removeUpdates(this);
}
}
});
}
else {
lat = l.getLatitude();
lng = l.getLongitude();
presenter.getFoot(userProfile.getToken(),"public",lat,lng,date);
}
EDIT:
If i restart the phone location works again but i dont take this as a solution since i cant tell all my clients to restart their phones everytime there is a problem
Try the blow code to get the location...and also ensure that location services are enabled in the device
locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 400, 1000, this); #Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 8);
mMap.animateCamera(cameraUpdate);
locationManager.removeUpdates(this);
}
#Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
#Override
public void onProviderEnabled(String s) {
}
#Override
public void onProviderDisabled(String s) {
}
I have a program that employs GPS to localize a person every 2 minutes. For that, the code is:
private boolean flagLocalizacion = false;
private LocationListener locationListener;
private Location ultimaLocalizacion;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
if (location!=null) {
if(ultimaLocalizacion == null && flagLocalizacion) {
ultimaLocalizacion = location;
Toast.makeText(getApplicationContext(), "Longitude: " + location.getLongitude() + "Latitude: " + location.getLatitude(), Toast.LENGTH_SHORT).show();
} else if ((ultimaLocalizacion.getLatitude() != location.getLatitude()
|| ultimaLocalizacion.getLongitude() != location.getLongitude()) && flagLocalizacion) {
ultimaLocalizacion = location;
Toast.makeText(getApplicationContext(), "Longitude: " + location.getLongitude() + "Latitude: " + location.getLatitude(), Toast.LENGTH_SHORT).show();
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {
System.out.println("gps");
}
public void onProviderDisabled(String provider) {
System.out.println("No gps");
}
}; Button botonComenzar = (Button) findViewById(R.id.bComenzar);
botonComenzar.setOnClickListener(new OnClickListener() {
#SuppressWarnings("static-access")
public void onClick(View v) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(locationManager.GPS_PROVIDER, 12000, 30, locationListener);
Toast.makeText(getApplicationContext(), "Activada Localizacion", Toast.LENGTH_SHORT).show();
flagLocalizacion = true;
}
});
My problem is:
This applicaction works correctly in version 2.2. But the software failed when I installed it in a phone that has 2.3.5., the The fail is that localice continually, not every 2 minutes. Do you have thoughts on why that is happening?
Thanks you.
Continuous GPS refresh (i.e., with an interval between GPS updates of 1 sec), regardless of the requested minTime, is a known issue with many Android phones prior to JellyBean.
Full discussion of this issue with the Android team is here:
https://android-review.googlesource.com/#/c/34230/
A new CTSVerifier test has been added in Android 4.1 JellyBean that should prevent this from happening on JellyBean and higher.
For devices pre-Jelly Bean that are affected by this, your only option for a workaround is to manually unregister and re-register the LocationListener at whatever time interval you want GPS to refresh.