在玩一个GPS的东西 获取Location一直为null 后来是从onLocationChanged里面拿location才搞定了 贴一下吧 代码太乱
- /**
- *主要是用户定位操作
- *@author hope
- */
- packagecom.jeedroid.tools;
- importjava.io.IOException;
- importjava.util.List;
- importjava.util.Locale;
- importandroid.content.Context;
- importandroid.location.Address;
- importandroid.location.Criteria;
- importandroid.location.Geocoder;
- importandroid.location.Location;
- importandroid.location.LocationListener;
- importandroid.location.LocationManager;
- importandroid.os.Bundle;
- importandroid.provider.Settings;
- importandroid.util.Log;
- publicclassLocationTools
- {
- privateLocationlocation;
- publicstaticLocationManagergetLocationManager(Contextcontext)
- {
- return(LocationManager)context.getSystemService(context.LOCATION_SERVICE);
- }
- //获取位置信息
- publicStringgetAddress(Contextcontext)
- {
- LocationManagerlocationManager=this.getLocationManager(context);
- if(!locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER))
- {
- //打开GPS需Android2.2以上系统支持
- android.provider.Settings.Secure.setLocationProviderEnabled(context.getContentResolver(),LocationManager.GPS_PROVIDER,false);
- }
- returndoWork(context);
- }
- privateStringdoWork(Contextcontext)
- {
- Stringaddres="";
- LocationManagerlocationManager=this.getLocationManager(context);
- Criteriacriteria=newCriteria();
- //获得最好的定位效果
- criteria.setAccuracy(Criteria.ACCURACY_FINE);
- criteria.setAltitudeRequired(false);
- criteria.setBearingRequired(false);
- criteria.setCostAllowed(false);
- //使用省电模式
- criteria.setPowerRequirement(Criteria.POWER_LOW);
- Stringprovider=locationManager.getBestProvider(criteria,true);
- Log.i("provider>>>>>>",provider);
- //获得当前位置location为空是一直取从onLocationChanged里面取
- while(location==null)
- {
- location=locationManager.getLastKnownLocation(provider);
- }
- //locationListener
- LocationListenerlocationListener=newLocationListener()
- {
- @Override
- publicvoidonLocationChanged(Locationlocation)
- {
- LocationTools.this.location=location;
- }
- @Override
- publicvoidonProviderDisabled(Stringprovider)
- {
- }
- @Override
- publicvoidonProviderEnabled(Stringprovider)
- {
- }
- @Override
- publicvoidonStatusChanged(Stringprovider,intstatus,Bundleextras)
- {
- }
- };
- locationManager.requestLocationUpdates(provider,1000,10,locationListener);
- Geocodergeo=newGeocoder(context,Locale.getDefault());
- try
- {
- List<Address>address=geo.getFromLocation(location.getLatitude(),location.getLongitude(),1);
- if(address.size()>0)
- {
- addres=address.get(0).getAddressLine(0);
- }
- }catch(IOExceptione)
- {
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- returnaddres;
- }
- }