2017-07-18 92 views
0

讓我首先承認搜索這個特定問題時有許多結果。然而,根據這些答案,作品我沒有嘗試過。有時我得到的位置,有時我沒有。如果我使用Location啓用/禁用,則撥打getLastKnownLocation時我總是會收到null。如果我有時手動撤消Location權限並重新啓用它,它就會起作用。我試過將LocationManager更改爲location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);,但它不起作用。getLastKnownLocation有時返回null

基本上,我做了以下內容:

public class GPSTracker implements LocationListener { 

    public static final int LOCATION_SETTINGS_REQUEST_CODE = 109; 

    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60; 

    private static boolean isGpsStatusChanged = false; 
    private static AlertDialog.Builder alertDialog; 

    private LocationManager locationManager; 
    private boolean canGetLocation = false; 
    private Location location; 
    private double latitude; 
    private double longitude; 
    private NewLocationListener newLocationListener; 

    public interface NewLocationListener { 
     void onLocationChanges(Location location); 
    } 

    public GPSTracker() { 

    } 

    @SuppressWarnings("all") 
    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context.LOCATION_SERVICE); 

      // getting GPS status 
      boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPSTracker", "Network"); 
        if (locationManager != null) { 
         Log.d("GPSTracker", "Network - location manager != null"); 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          Log.d("GPSTracker", "Network - last known location != null"); 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
          newLocationListener.onLocationChanges(location); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPSTracker", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          Log.d("LastKnownLocation", "Location: " + locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
           newLocationListener.onLocationChanges(location); 
          } 
         } 
        } 
       } 
      } 
     } catch (Exception e) { 
      Log.e(Constants.TAG, e.getMessage(), e); 
     } 

     return location; 
    } 

    public static boolean isGpsEnabled() { 
     LocationManager locationManager = (LocationManager) BaseApplication.getContext().getSystemService(Context 
       .LOCATION_SERVICE); 
     return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); 
    } 

    @SuppressWarnings("all") 
    public void stopUsingGPS() { 
     if (locationManager != null) { 
      locationManager.removeUpdates(GPSTracker.this); 
     } 
    } 

    public double getLatitude() { 
     if (location != null) { 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    public double getLongitude() { 
     if (location != null) { 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    public void setNewLocationListener(NewLocationListener newLocationListener) { 
     this.newLocationListener = newLocationListener; 
    } 

    public void removeLocationListener() { 
     this.newLocationListener = null; 
    } 

    @SuppressWarnings("InlinedApi") 
    public void showSettingsAlert(final Context context) { 
     if (alertDialog != null) { 
      return; 
     } 

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { 
      alertDialog = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert); 
     } else { 
      alertDialog = new AlertDialog.Builder(context); 
     } 
     alertDialog.setTitle(R.string.gps_window_title); 
     alertDialog.setMessage(R.string.gps_window_message); 

     alertDialog.setPositiveButton(R.string.gps_window_button_positive, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       ((Activity) context).startActivityForResult(intent, LOCATION_SETTINGS_REQUEST_CODE); 
      } 
     }); 

     alertDialog.setNegativeButton(R.string.gps_window_button_negative, new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     alertDialog.show().setOnDismissListener(new DialogInterface.OnDismissListener() { 
      @Override 
      public void onDismiss(DialogInterface dialog) { 
       alertDialog = null; 
      } 
     }); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
     if (newLocationListener != null) { 
      newLocationListener.onLocationChanges(location); 
     } 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) { 
    } 

    public static boolean isGpsStatusChanged() { 
     return isGpsStatusChanged; 
    } 

    public static void setIsGpsStatusChanged(boolean isGpsStatusChanged) { 
     GPSTracker.isGpsStatusChanged = isGpsStatusChanged; 
    } 
} 

然後在我的fragment

private void statGPSLocationTracking() { 

    Log.d(Constants.TAG, "start gps update"); 
    // check if GPS enabled 
    gpsTracker = new GPSTracker(); 
    gpsTracker.setNewLocationListener(newLocationListener); 
    gpsTracker.getLocation(); 

    if (!gpsTracker.canGetLocation()) { 
     Log.d(Constants.TAG, "GPS not enabled, show enable dialog"); 
     // stop the gps tracker(removes the location update listeners) 
     gpsTracker.stopUsingGPS(); 

     // ask user to enable location 
     gpsTracker.showSettingsAlert(getActivity()); 
    } 
} 

private GPSTracker.NewLocationListener newLocationListener = new GPSTracker.NewLocationListener() { 
    @Override 
    public void onLocationChanges(Location loc) { 
     if (getActivity() == null) { 
      return; 
     } 
     // GPS location determined, load the web page and pass the coordinates in the header location section 
     Log.d(Constants.TAG, "Location listener onLocationChanges: " + loc); 
     infoManager.setCurrentLocation(loc); 
     checkRadioInfoNeeded(); 

     // stop the gps tracker(removes the location update listeners) 
     gpsTracker.stopUsingGPS(); 
    } 
}; 
+0

[LocationManager的getLastKnownLocation的可靠性如何以及它更新的頻率如何?](https://stackoverflow.com/questions/7423624/how-reliable-is-locationmanagers-getlastknownlocation-and-how-often-is -it-updat) – j4rey89

回答

0

入住這

public Location getLocation(){ 
     try{ 

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

      // getting GPS status 
      boolean isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      boolean isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 
      if(!isGPSEnabled && !isNetworkEnabled){ 

      }else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 

      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 

     }catch (Exception e){ 
      e.printStackTrace(); 
     } 
     return location; 

    } 
+0

它仍然是'null'。 – JackW5808

+0

位置許可是否在設備中給出? –

+0

並確保您的設備存儲最後一個已知位置。如果不去谷歌地圖並用GPS定位我的位置。 –

0

沒有這個位置的權限android.Manifest.permission.ACCESS_FINE_LOCATIONgetLastKnownLocation()總會返回null。

getLastKnownLocation()不立即返回位置,需要一些時間。

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60; 

private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 0; 
private static final long MIN_TIME_BW_UPDATES = 5 * 1000; 

同時刪除您的代碼從網絡獲取位置。去谷歌地圖,看看地圖是否能夠檢測到您的當前位置。如果您的地圖能夠獲取位置,那麼您的代碼也應該獲取位置位置斷點並查看實際問題的位置。

+0

我試過了,它仍然無法正常工作。我在這裏得到if(locationManager!= null)location = locationManager .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);''而location'爲null。 – JackW5808

+0

@ JackW5808你可以在其他設備上嘗試相同的代碼並讓我們知道結果嗎?你也可以告訴我們你的設備名稱嗎? –

+0

我試了模擬器Nexus 5X和華爲P8。我現在將在另一臺設備上進行測試。 – JackW5808

相關問題