0

我在获取用户位置(我的位置)时遇到问题。我的代码是

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();
} 

我的问题是我在null启用应用程序消息提供程序时获取位置。我在这段代码中没有发现任何问题。我还在设备上对其进行了测试,它显示提供程序已启用并且找不到位置。

我还没有在课堂上实现位置监听器。是否有必要在我的班级中实现位置监听器?

4

1 回答 1

3

您只能从电话中获取最后一个已知位置。如果这是 null,如果没有最后一个已知位置可用,则您不会尝试以任何其他方式接收位置。

您应该实现一个 LocationListener 并根据本指南将其注册以接收位置更新:http: //developer.android.com/guide/topics/location/obtaining-user-location.html这将导致手机尝试获取用户定位并以 Location 对象的形式将其交给您的应用程序。

于 2011-01-13T09:18:42.300 回答