Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wifi provider onLocationChanged is never called

I got a weird problem. I uses wifi to retrieve user location. I have tested on several phones; on some of them, I could never get a location update. it seemed that the method onLocationChanged is never called. My code is attached below.. Any suggestions appreciated!!!

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);

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

  String provider = locationManager.NETWORK_PROVIDER;
  Location l = locationManager.getLastKnownLocation(provider);

  updateWithNewLocation(l);

  locationManager.requestLocationUpdates(provider, 0, 0,
                                       locationListener);
}

private void updateWithNewLocation(Location location) {
  TextView myLocationText;
  myLocationText = (TextView)findViewById(R.id.myLocationText);

  String latLongString = "No location found";
  if (location != null) {
    double lat = location.getLatitude();
    double lng = location.getLongitude();
    latLongString = "Lat:" + lat + "\nLong:" + lng;
  }

  myLocationText.setText("Your Current Position is:\n" +
                       latLongString);
}

private final LocationListener locationListener = new LocationListener() {
  public void onLocationChanged(Location location) {
    updateWithNewLocation(location);
    Log.i("onLocationChanged", "onLocationChanged");
    Toast.makeText(getApplicationContext(), "location changed", 
            Toast.LENGTH_SHORT).show();
  }

public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, 
                            Bundle extras) {}

};

Manifest

<uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION"
/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/> 
like image 397
Kelsie Avatar asked Jun 25 '12 03:06

Kelsie


1 Answers

My guess is that the phones on which you don't get location updates from do not have proper data connection. Network Provider needs GSM/3G or WiFi data connection to retrieve a location fix from Google servers using phones's cell/wifi data. You can use the method below to check this.

public boolean isOnline() {
ConnectivityManager cm =
    (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
    return true;
}
return false;

}

like image 68
Behzad Momahed Heravi Avatar answered Nov 07 '22 09:11

Behzad Momahed Heravi