2016-03-05 11 views
0

我有一個程序,獲取用戶的經度和緯度。當我打開GPS或網絡提供商新的,我的程序不會得到經度和緯度

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 

     // Create a criteria object to retrieve provider 
     Criteria criteria = new Criteria(); 
     // Get the name of the best provider 
     String provider = locationManager.getBestProvider(criteria, true); 
     // Get Current Location 
     if (ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
      // TODO: Consider calling 
      // ActivityCompat#requestPermissions 
      // here to request the missing permissions, and then overriding 
      // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
      //           int[] grantResults) 
      // to handle the case where the user grants the permission. See the documentation 
      // for ActivityCompat#requestPermissions for more details. 
     } 
     Location myLocation = locationManager.getLastKnownLocation(provider); 
    Location myLocation = locationManager.getLastKnownLocation(provider); 
       boolean netEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
       boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
       if (netEnabled) { 
        if (isGPSEnabled) { 
         latitude = myLocation.getLatitude(); 

         longitude = myLocation.getLongitude() 
        } else if (!isGPSEnabled) { 
         locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 
         Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 

         } else { 


          // displayPromptForEnablingGPS(MapsActivity.this); 
         } 
        } 
       } else if (!netEnabled) { 


        if (isGPSEnabled) { 
         latitude = myLocation.getLatitude(); 

         // Get longitude of the current location 
         longitude = myLocation.getLongitude(); 


        } else { 
         // displayPromptForEnablingGPS(MapsActivity.this); 
        } 

       } 

(displayPromptForEnablingGPS爲ACTION_LOCATION_SOURCE_SETTINGS)

在程序中,如果GPS和網絡提供商都關閉,將打開一個窗口,用於對它們進行切換。當我第一次開啓GPS時,如果(GPSEnabled)方法(緯度= myLocation.getLatitude()上的錯誤)首先給出錯誤。我無法獲得經度和緯度。當我只接入網絡提供商時也是如此。它給「位置」變量null。但是,如果我打開Goog​​le地圖,它會開始獲取經度和緯度。

問題是什麼?這是手機的問題,或者我必須通過編寫任何代碼使GPS運行?

感謝您的幫助。

回答

0

如果以前沒有位置信息,該方法將返回空值。 最好是讓最後一個已知的位置遍歷所有啓用的提供者,因爲這種情況下 沒有GPS和網絡提供者。 >>上SO 鏈接這只是最好添加處理這種情況下,如果 (netEnabled & & isGPSEnabled!){// 沒有網絡提供商啓用

上面的示例代碼:here

相關問題