سؤال

I have a problem in getting the user's location (my location). My code is

double lat;
double lng;
LocationManager locationManager;
String context = Context.LOCATION_SERVICE; 
locationManager = (LocationManager)getSystemService(context);
String provider = LocationManager.GPS_PROVIDER;
Location location = locationManager.getLastKnownLocation(provider);
if(!locationManager.isProviderEnabled(provider)){
 locationManager.setTestProviderEnabled(provider, true);
}
boolean enabled = locationManager.isProviderEnabled(provider);
if(enabled){
        Toast.makeText(LoginActivity.this,"provider enabled",Toast.LENGTH_LONG).show();
}
else{
    Toast.makeText(LoginActivity.this,"provider disabled",Toast.LENGTH_LONG).show();
}
if(location!=null){
  lat = location.getLatitude();
  lng = location.getLongitude();
  AlertDialog.Builder ab=new AlertDialog.Builder(LoginActivity.this);
  ab.setMessage(Html.fromHtml("<b><font color=#ff0000>Location" +"</font></b><br>"
            +location.toString()+"<br>Latitude: "+lat
                +"<br>Longitude "+lng));
  ab.setPositiveButton("ok",null );
  Toast.makeText(LoginActivity.this,"You are at     "+location.toString(),Toast.LENGTH_LONG).show();
}
else{
    Toast.makeText(LoginActivity.this,"Location not found",Toast.LENGTH_LONG).show();
} 

My problem is I am getting the location as null while the application message provider is enabled. I have not found any problem in this code. I have also tested it on a device, it shows the provider is enabled and the location isn't found.

I have not implemented the location listener in the class. Is it necessary to implement location listener in my class?

هل كانت مفيدة؟

المحلول

You are only getting the last known location from the phone. If this is null, which it is if no last known location is available, you are not trying to receive locations in any other way.

You should implement a LocationListener an register it to receive location updates according to this guide: http://developer.android.com/guide/topics/location/obtaining-user-location.html This will cause the phone to try to get the users location and hand it over to your application in the form of a Location object.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top