android – onLocationChanged() never called-ThrowExceptions

Exception or error:

I am writing a code that brings current location but it is not giving me the location because it never calls onLocationChanged() .Is there any way to find the location.

mobileLocation is coming 0 for this case, so the execution goes to the else block.

My code is

public class FindLocation {
private LocationManager locManager;
private LocationListener locListener;
private Location mobileLocation;
private String provider;

public FindLocation(Context ctx){
    locManager = (LocationManager) ctx.getSystemService(Context.LOCATION_SERVICE);
    locListener = new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(Location location) {
            System.out.println("mobile location is in listener="+location);
            mobileLocation = location;
        }
    };
    locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);              
    if (mobileLocation != null) {
        locManager.removeUpdates(locListener); 
        String londitude = "Londitude: " + mobileLocation.getLongitude();
        String latitude = "Latitude: " + mobileLocation.getLatitude();
        String altitiude = "Altitiude: " + mobileLocation.getAltitude();
        String accuracy = "Accuracy: " + mobileLocation.getAccuracy();
        String time = "Time: " + mobileLocation.getTime();
        Toast.makeText(ctx, "Latitude is = "+latitude +"Longitude is ="+londitude, Toast.LENGTH_LONG).show();
    } else {
        System.out.println("in find location 4");
        Toast.makeText(ctx, "Sorry location is not determined", Toast.LENGTH_LONG).show();
    }
}
   }
How to solve:

Do you never get a location or only as you write in your comment “sometimes it gets location but not at the time of click.”?

Might be that your code is faster than LocationManager, which might not yet have called onLocationChanged(). Change your code in order to get the last known location, or wait until your locListener was called:

locManager.requestLocationUpdates(
  LocationManager.GPS_PROVIDER, 1000, 1, locListener);
mobileLocation = locManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (mobileLocation != null) {

###

i run my app on real device .
i use network instead of GPS and onLocationChanged is called:

locMan.requestSingleUpdate(LocationManager.NETWORK_PROVIDER, this, null);

###

I thing you forgot permission

<uses-permission android:name="android.permission.ACCESS_GPS" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.INTERNET" />

OR

Declare Proper Class like

public class MyLocationListener implements LocationListener {
@Override
  public void onLocationChanged(Location arg0) {
    latitude = arg0.getLatitude();
    longitude = arg0.getLongitude();
  }

}

###

LocationManager.NETWORK_PROVIDER need network, but it is real, not precise; if you want to use LocationManager.GPS_PROVIDER, the situation must be outdoor instead of indoor, because GPS location need satellite, if you are in any building, the satellite cannot find you!

###

Directly after locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener), add the following code:

locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 1, locListener);

EDIT: corrected the code thanks to the comment by @Fabian Streitel.

###

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.util.Log;

import org.json.JSONObject;

import java.util.List;


public class AndroidLocationServices  extends Service {

    PowerManager.WakeLock wakeLock;
    String MODULE="AndroidLocationServices",TAG="";
    private LocationManager locationManager;
    double getLattitude=0,getLogitude=0;
    private static final long MIN_TIME_BW_UPDATES = 1; // 1 minute
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0;


    public AndroidLocationServices() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        preferences=getSharedPreferences(GlobalConfig.PREF_NAME, MODE_PRIVATE);
        PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);

        wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");

        // Toast.makeText(getApplicationContext(), "Service Created",
        // Toast.LENGTH_SHORT).show();

        Log.e("Google", "Service Created");

    }

    @Override
    @Deprecated
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);

        Log.e("Google", "Service Started");

        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);

        //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500, 0, listener);
        locationManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER,  MIN_TIME_BW_UPDATES,  MIN_DISTANCE_CHANGE_FOR_UPDATES, listener);


    }



    public LocationListener listener = new LocationListener() {

        @Override
        public void onLocationChanged(Location location) {
            // TODO Auto-generated method stub

            Log.e("Google", "Location Changed");
            location.setAccuracy(100);

            if (location == null)
                return;
                    getLattitude=location.getLatitude();
                    getLogitude=location.getLongitude();

                    Log.e("latitude", getLattitude + "");
                    Log.e("longitude", getLogitude + "");


        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }
    };

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();

//        wakeLock.release();

    }


}

Manifest:

  <service android:name=".services.AndroidLocationServices"/>

Start Service before use:

 startService(new Intent(this, AndroidLocationServices.class));

###

In my case the app was not asking for permissions. Although I have added the permissions in menifest file. So I was not able to allow my app to access the location.

As a fix, I manually went to: Settings->Permissions->Your location and enabled the location permission for my under-development app. And that fixed my problem.

I assume that this issue is only when the app is installed through Android Studio. I hope it will not occur when the app is installed from Google Play.

Leave a Reply

Your email address will not be published. Required fields are marked *