location with internet service provider(network provider) - android

Hello I have class that looks up for your location, first with network provider, then waits for GPS provider info. I don't know why, but I never get information from network provider, GPS works well, when signal is acquired.
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
Map.MyPositionlatitude = location.getLatitude();
Map.MyPositionlongitude = location.getLongitude();
}
}
}

use google play serivces it is more simple

Related

Memory leak in Location manager

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

android get location in background and update listview

I'm trying to program an application which is using the current location from the user and calculating the distance and writes it into my listview.
The location doesn't have to be very accurate and i only want to fetch a new location when the list is refreshed or on app start, not continously.
My problem is that the locationlistener with gps takes too long to find a location and i have to update my list a lot before it is showing the right distance.
I was thinking about implementing a background task which gets the location and updates the list automatically when it found the position. Would that be a solution?
Is there any option to get a location faster, even if it is not as accurate as gps?
what i have so far on my location listener:
public class MyLocationListener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
lat = location.getLatitude();
lng = location.getLongitude();
myLoc.setLatitude(lat);
myLoc.setLongitude(lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
in this method i'm calling the locationmanager and listener and creating the listview with the distance
public void getList(){
locationManager = (LocationManager) getActivity().getSystemService(getActivity().LOCATION_SERVICE);
locationManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
//... creating the list with distance and so on
}
i hope you can give me some hints how i can implement this that i will work as described above or tell me what i should use instead.
thanks :)
1). You can use LocationManager.NETWORK_PROVIDER
This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.
eg:- locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
2). If you want to use background task then use this service
public class LocationFinder extends Service {
public static double lat, lng;
LocationManager locationManager;
public void onDestroy() {
super.onDestroy();
if (locationManager != null && locationListener != null) {
locationManager.removeUpdates(locationListener);
}
}
#Override
public void onCreate() {
Log.v("location", "===>location ed onCreate " + lat);
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
Log.v("location", "===>location ed onStartCommand " + lat + "==>" + lng);
new Handler().post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
getLocation();
}
});
return START_STICKY;
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
updateWithNewLocation(location);
}
public void onProviderDisabled(String provider) {
updateWithNewLocation(null);
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
};
private void getLocation() {
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager) getSystemService(context);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
if (locationManager != null) {
String provider = locationManager.getBestProvider(criteria, true);
if (provider != null) {
Location location = locationManager.getLastKnownLocation(provider);
updateWithNewLocation(location);
locationManager.requestLocationUpdates(provider, 500, 50, locationListener);
} else {
if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 50, locationListener);
} else if (locationManager.isProviderEnabled(LocationManager.PASSIVE_PROVIDER)) {
locationManager.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 500, 50, locationListener);
}
}
}
}
private void updateWithNewLocation(Location location) {
if (location != null) {
Log.v("location", "===>location ed " + lat);
lat = location.getLatitude();
lng = location.getLongitude();
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}

android GPS current Location null value

i use the following code for getting the current latitude and longitude in services but it always return null. please help me.
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
System.out.println("provider "+provider);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Try this code for current location:
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10,
10, mlocListener);
public class MyLocationListener implements LocationListener {
public void onProviderDisabled(String provider)
{
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(
VisualCV.this);
dlgAlert.setMessage("Gps Disabled ");
dlgAlert.setTitle("Message");
dlgAlert.setPositiveButton("OK", null);
dlgAlert.setCancelable(true);
dlgAlert.create().show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps enabled", Toast.LENGTH_SHORT ).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
public void onLocationChanged(Location loc)
{
// TODO Auto-generated method stub
Latitud = loc.getLatitude();
longtitude = loc.getLongitude();
lang = String.format("%.4f", longtitude);//LONGITUDE
lati = String.format("%.4f", Latitud);//LATITUDE
}
}
Use this piece of code may be it may help you
import com.example.ConfigClass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GpsListener {
public static GpsListener refrence = null ;
public LocationManager locationManager = null;
public LocationListener locationListener = null;
public Location location = null;
public static GpsListener getInstance(){
if(refrence == null){
refrence = new GpsListener();
}
return refrence;
}
public void startGpsCallBack(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
public class mylocationlistener implements LocationListener {
#Override
public void onLocationChanged(Location location) {
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
public void stopGpsCallBack(){
if (locationManager != null) {
locationManager.removeUpdates(locationListener);
}
}
public void startGpsCallbackAgain(Context activityContext){
locationManager = (LocationManager) activityContext.getSystemService(Context.LOCATION_SERVICE);
locationListener = new mylocationlistener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 0, 0, locationListener);
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
ConfigClass.latitudeValue = location.getLatitude();
ConfigClass.longitudeValue = location.getLongitude();
}
}
}
This is my code
First startGpsCallBack, then stop it and then call startGPSCallBackAgain method
Check it and let me know if this solves your problem
Try this.
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Use the LocationManager class to obtain GPS locations */
LocationManager mlocManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new MyLocationListener();
mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 0, 0, mlocListener);
}
/* Class My Location Listener */
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}

Current user location is not retrieving

This is my last question about gps
Getting 0.0 for latitude and longitude while showing current location in map
Now here is the code I'm using to get the user's current location.
LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crta = new Criteria();
crta.setAccuracy(Criteria.ACCURACY_FINE);
crta.setAltitudeRequired(false);
crta.setBearingRequired(false);
crta.setCostAllowed(true);
crta.setPowerRequirement(Criteria.POWER_LOW);
String provider = mlocManager.getBestProvider(crta, true);
Location loc = null;
if (provider != null) {
loc = mlocManager.getLastKnownLocation(provider);
}
LocationListener mlocListener = new MyLocationListener();
mlocListener.onLocationChanged(loc);
mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
2000, 10, mlocListener);
public class MyLocationListener implements LocationListener{
public MyLocationListener() {
}
#Override
public void onLocationChanged(Location loc) {
if (null != loc) {
String Text = "Your current location is: \n" + "Latitude = \n"
+ loc.getLatitude() + "\nLongitude = \n" + loc.getLongitude();
Toast.makeText(getApplicationContext(),Text,Toast.LENGTH_SHORT).show();
GeoPoint myGeoPoint = new GeoPoint((int)(loc.getLatitude()*1E6),(int)(loc.getLongitude()*1E6));
mpc.animateTo(myGeoPoint);
mpc.setZoom(10);
objMapView.invalidate();
}
}
#Override
public void onProviderDisabled(String provider){
Toast.makeText(getApplicationContext(), "gps disabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(getApplicationContext(), "gps enabled",Toast.LENGTH_SHORT).show();
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
Now the problem I'm facing is, it is not showing me the current location when the gps is turned on. The loc object , loc = mlocManager.getLastKnownLocation(provider); always returns null. I got the value for provider as gps.
But if I turn of my gps connection, the same loc object will have relevant information and it works partiall correct. That means, it gives me the nearest location. I mean the full city location where I am sitting.
But if I on my gps connection, it does not give me even the city location also, does not enters if loop only inside location listener class. I am not getting what is going wrong here.
Any one can tell me how to solve it?
Update:
This is the value I get for loc object if my gps is off
Location[mProvider=network,mTime=1331718353322,mLatitude=12.9053401,mLongitude=74.8359128,mHasAltitude=false,mAltitude=0.0,mHasSpeed=false,mSpeed=0.0,mHasBearing=false,mBearing=0.0,mHasAccuracy=true,mAccuracy=36.0,mExtras=Bundle[mParcelledData.dataSize=148]].
But if the gps is on, loca return null
CustomLocationManager.Java
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class CustomLocationManager {
private LocationManager mLocationManager;
private LocationValue locationValue;
private Location networkLocation = null;
private Location gpsLocation = null;
private Timer mTimer;
private boolean isGpsEnabled = false;
private boolean isNetworkEnabled = false;
private static CustomLocationManager _instance;
private CustomLocationManager() {}
public static CustomLocationManager getCustomLocationManager() {
if (_instance == null) {
_instance = new CustomLocationManager();
}
return _instance;
}
public LocationManager getLocationManager(Context context) {
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
return mLocationManager;
}
public boolean getCurrentLocation(Context context, LocationValue result) {
locationValue = result;
if (mLocationManager == null)
mLocationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
try {
isGpsEnabled = mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
} catch (Exception ex) {}
try {
isNetworkEnabled = mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!isGpsEnabled && !isNetworkEnabled)
return false;
if (isGpsEnabled)
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, gpsLocationListener);
if (isNetworkEnabled)
mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, networkLocationListener);
mTimer = new Timer();
mTimer.schedule(new GetLastKnownLocation(), 20000);
return true;
}
LocationListener gpsLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(networkLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private LocationListener networkLocationListener = new LocationListener() {
public void onLocationChanged(Location location) {
mTimer.cancel();
locationValue.getCurrentLocation(location);
mLocationManager.removeUpdates(this);
mLocationManager.removeUpdates(gpsLocationListener);
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
private class GetLastKnownLocation extends TimerTask {
CurrentLocationHandler handler;
GetLastKnownLocation() {
handler = new CurrentLocationHandler();
}
#Override
public void run() {
mLocationManager.removeUpdates(gpsLocationListener);
mLocationManager.removeUpdates(networkLocationListener);
if (isGpsEnabled)
gpsLocation = mLocationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (isNetworkEnabled)
networkLocation = mLocationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
handler.sendEmptyMessage(0);
}
}
private class CurrentLocationHandler extends Handler {
#Override
public final void handleMessage(Message msg) {
if (gpsLocation != null && networkLocation != null) {
if (gpsLocation.getTime() > networkLocation.getTime())
locationValue.getCurrentLocation(gpsLocation);
else
locationValue.getCurrentLocation(networkLocation);
return;
}
if (gpsLocation != null) {
locationValue.getCurrentLocation(gpsLocation);
return;
}
if (networkLocation != null) {
locationValue.getCurrentLocation(networkLocation);
return;
}
locationValue.getCurrentLocation(null);
}
}
}
LocationValue.Java
import android.location.Location;
public abstract class LocationValue {
public abstract void getCurrentLocation(Location location);
}
YourActivity.Java
private void getCurrentLocation() {
CustomLocationManager.getCustomLocationManager().getCurrentLocation(this, locationValue);
}
public LocationValue locationValue = new LocationValue() {
#Override
public void getCurrentLocation(Location location) {
// You will get location here if the GPS is enabled
if(location != null) {
Log.d("LOCATION", location.getLatitude() + ", " + location.getLongitude());
}
}
};
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
First of all I'm not familiar with the Android location API, but did you try the GPS outside? Since GPS doesn't work inside buildings, it's pretty hard to retrieve the location of your mobile device using only your GPS. When indoors, typically your "GPS" position is determined using your WiFi acces point connection instead.

Strange issue in finding GPS

Hai all i want to find current GPS location, i have used the following code.
public class GPSManager
{
private static final int gpsMinTime = 500;
private static final int gpsMinDistance = 0;
private LocationManager locationManager = null;
private LocationListener locationListener = null;
private GPSCallback gpsCallback = null;
public GPSManager()
{
locationListener = new LocationListener()
{
public void onProviderDisabled(final String provider)
{
}
public void onProviderEnabled(final String provider)
{
}
public void onStatusChanged(final String provider, final int status, final Bundle extras)
{
}
public void onLocationChanged(final Location location)
{
location.getLatitude();
location.getLongitude();
if (location != null && gpsCallback != null)
{
Log.e("if location "+location,"if gpscallback"+gpsCallback);
gpsCallback.onGPSUpdate(location);
location.getLatitude();
location.getLongitude();
}
else{
Log.e("else location "+location,"else gpscallback"+gpsCallback);
}
}
};
}
public void startListening(final Activity activity)
{
if (locationManager == null)
{
locationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
}
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
final String bestProvider = locationManager.getBestProvider(criteria, true);
if (bestProvider != null && bestProvider.length() > 0)
{
locationManager.requestLocationUpdates(bestProvider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
else
{
final List<String> providers = locationManager.getProviders(true);
for (final String provider : providers)
{
locationManager.requestLocationUpdates(provider, GPSManager.gpsMinTime,
GPSManager.gpsMinDistance, locationListener);
}
}
}
public void stopListening()
{
try
{
if (locationManager != null && locationListener != null)
{
locationManager.removeUpdates(locationListener);
}
locationManager = null;
}
catch (final Exception ex)
{
}
}
public void setGPSCallback(final GPSCallback gpsCallback)
{
this.gpsCallback = gpsCallback;
}
public GPSCallback getGPSCallback()
{
return gpsCallback;
}
But strange issue is it is working only when GPS in mobile is off mode. If GPS in device is in on Mode it is not working.
Can anybody please tell me what is the issue with my code?
Please help me... thanks in advance.
The problem should be the power requirement. You're requesting for everything that matchs the gps provider ( Location fine .... ) but gps is power consuming so try to remove that line or setting the criteria to POWER_HIGH

Categories

Resources