android獲取位置location爲null的問題

  12:38:542016-12-23

不少人常常遇到這種問題,主要是獲取到位置的信息爲null,第一個主要要有權限  android

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
      <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION"/>
git

第二個咱們調用的方法是 Location location = locationManager.getLastKnownLocation(provider);ide

 這個方法主要是獲取上一次的經緯度信息,上一次的話確定是空的啦。。這是要註冊一下獲取事件的監聽器測試

等一會之後就能夠拿到了經緯度了。。因此說一開始不要着急獲取經緯度。。等待一會就有了。。不會報空指針異常。spa

LocationManager locationManager;
   String serviceName = Context.LOCATION_SERVICE;
   locationManager = (LocationManager) con.getSystemService(serviceName); // 查找到服務信息
   //locationManager.setTestProviderEnabled("gps", true);
  
   locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 3000, 0, mLocationListener01);
   locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 3000, 0, mLocationListener01);
指針

 

 

獲取數據和監聽器blog

 

  * 經過location獲取當前設備的具體位置
   *
   * @param location
   * @param rowId
   * @param params
   * @param rowId
   */
 private Location updateToNewLocation(Location location) {
  System.out.println("--------zhixing--2--------");
   String latLongString;
   double lat = 0;
   double lng=0;
  
   if (location != null) {
    lat = location.getLatitude();
    lng = location.getLongitude();
    latLongString = "緯度:" + lat + "\n經度:" + lng;
    System.out.println("經度:"+lng+"緯度:"+lat);
   } else {
    latLongString = "沒法獲取地理信息,請稍後...";
   }
   if(lat!=0){
    System.out.println("--------反饋信息----------"+ String.valueOf(lat));
   }
  
   Toast.makeText(getApplicationContext(), latLongString, Toast.LENGTH_SHORT).show();
 
   return location;
  
 }
  
      // 設置監聽器,自動更新的最小時間爲間隔N秒(1秒爲1*1000,這樣寫主要爲了方便)或最小位移變化超過N米
 public final LocationListener mLocationListener01 = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            updateToNewLocation(location);
        }
   
事件

        @Override
        public void onProviderDisabled(String provider) {
         updateToNewLocation(null);
        }
get

        @Override
        public void onProviderEnabled(String provider) {}
it

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}};通過測試。。沒有問題。。但願幫到大家。。。

相關文章
相關標籤/搜索