问题描述
- Android获取当前位置,location为空
-
MainActivity.java:
public class MainActivity extends Activity {
LocationManager locationManager ;
String provider;
TextView location_msg;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
location_msg = (TextView) findViewById(R.id.location_msg);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
List providerList = locationManager.getProviders(true);
if(providerList.contains(LocationManager.GPS_PROVIDER))
{
provider = LocationManager.GPS_PROVIDER;} else if(providerList.contains(LocationManager.NETWORK_PROVIDER)) { provider = LocationManager.NETWORK_PROVIDER; } else { Toast.makeText(MainActivity.this, "here are no useful location service", 1000).show(); return; } Location location = locationManager.getLastKnownLocation(provider); if(location!=null) { Log.i(">>>>>>>MainActivity", "显示位置信息,信息呢?"); showLocation(location); } else { Log.i(">>>>>>>MainActivity", "信息显示为空。。。。。。"); } locationManager.requestLocationUpdates(provider, 5000, 1, listener); } private void showLocation(Location location) { String position = "latitude is " + location.getLatitude() + " " + "longitude is " + location.getLongitude(); location_msg.setText("HELLO WORLD"); location_msg.setTextColor(Color.BLUE); //Log.i(">>>>>>>MainActivity", "显示位置信息,信息呢?"); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(locationManager!=null) { locationManager.removeUpdates(listener); } } LocationListener listener = 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) { showLocation(location); } };
}
布局文件为:一个TextView显示地理位置:经度和纬度
AndroidManifest.xml文件添加访问位置权限:
解决方案
? ? ?通过最后一次的地理位置来获得Location对象:location = locationManager.getLastKnownLocation(provider);得出location为空。查看各种资料发现,getLastKnownLocation仅仅是获取当缓存中的上一次打开地图缓存起来的位置,不可能一次就能获取,那唯有location为空的时候继续......
答案就在这里:Android获取当前位置,location为空
解决方案二:
如果以前没有获得过,那你用过去最后一次是获取不到的,你就在监听事件中获取就行了
解决方案三:
http://blog.csdn.net/column/details/android-jacksen-map.html
参考一下。
时间: 2024-09-20 13:11:07