2017-07-25 30 views
-2

我打開地圖活動後無法立即獲取當前位置。 儘管它用藍點標記顯示當前位置。一旦我打開我的地圖活動,就無法獲取當前位置

我看到的異常信息:顯示java.lang.NullPointerException:嘗試調用虛擬方法「雙android.location.Location.getLatitude()」上的空對象引用

這需要大量的時間來獲取座標。爲此,我必須移動手機並等待。

這是我爲它的代碼:

if (Build.VERSION.SDK_INT < 25) { 
     if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) { 
      // Ask for permission 

      ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
      if (ContextCompat.checkSelfPermission(this, 
Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED){ 
       ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
      } 

     } else { 


locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 
0, locationListener); 

      lastKnownLocation = 
locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); 
try { 
pDialog.hide(); 
locate = new LatLng(lastKnownLocation.getLatitude(), 
lastKnownLocation.getLongitude()); 

mMap.clear(); 
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13)); 
originMarkers.add(mMap.addMarker(new MarkerOptions() 
     .title("Your Location") 
     .position(locate))); 

origin_lati = "" + lastKnownLocation.getLatitude(); 
origin_longi = "" + lastKnownLocation.getLongitude(); 

Log.e("Lati Longi", origin_lati+", "+origin_longi); 
}catch (Exception e){ 
Log.e("Exception", e.toString()); 
} 

     } 
    } 
+2

爲什麼不使用新的fusedLocationApi進行位置更新? – sumit

+0

我對這個概念很陌生。這個怎麼用? –

+0

我是否必須更改完整的代碼? –

回答

0

使用此:

首先創建谷歌API客戶端:

/** 
    * Builds a GoogleApiClient. 
    * Uses the addApi() method to request the Google Places API and the Fused Location Provider. 
    */ 
    private synchronized void buildGoogleApiClient() { 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .enableAutoManage(this /* FragmentActivity */, 
         this /* OnConnectionFailedListener */) 
       .addConnectionCallbacks(this) 
       .addApi(LocationServices.API) 
       .addApi(Places.GEO_DATA_API) 
       .addApi(Places.PLACE_DETECTION_API) 
       .build(); 
     createLocationRequest(); 
    } 

/** 
    * Sets up the location request. 
    */ 
    private void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 

     /* 
     * Sets the desired interval for active location updates. This interval is 
     * inexact. You may not receive updates at all if no location sources are available, or 
     * you may receive them slower than requested. You may also receive updates faster than 
     * requested if other applications are requesting location at a faster interval. 
     */ 
     mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS); 

     /* 
     * Sets the fastest rate for active location updates. This interval is exact, and your 
     * application will never receive updates faster than this value. 
     */ 
     mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS); 

     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 

然後獲得位置:

/** 
    * Gets the current location of the device and starts the location update notifications. 
    */ 
    private void getDeviceLocation() { 
     /* 
     * Request location permission, so that we can get the location of the 
     * device. The result of the permission request is handled by a callback, 
     * onRequestPermissionsResult. 
     */ 
     if (ContextCompat.checkSelfPermission(this.getApplicationContext(), 
       android.Manifest.permission.ACCESS_FINE_LOCATION) 
       == PackageManager.PERMISSION_GRANTED) { 
      mLocationPermissionGranted = true; 
     } else { 
      ActivityCompat.requestPermissions(this, 
        new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, 
        PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION); 
     } 
     /* 
     * Get the best and most recent location of the device, which may be null in rare 
     * cases when a location is not available. 
     * Also request regular updates about the device location. 
     */ 
     if (mLocationPermissionGranted) { 
      mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient); 
      LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, 
        mLocationRequest, this); 
     } 
    } 



/** 
    * Handles the result of the request for location permissions. 
    */ 
    @Override 
    public void onRequestPermissionsResult(int requestCode, 
              @NonNull String permissions[], 
              @NonNull int[] grantResults) { 
     mLocationPermissionGranted = false; 
     switch (requestCode) { 
      case PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION: { 
       // If request is cancelled, the result arrays are empty. 
       if (grantResults.length > 0 
         && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 
        mLocationPermissionGranted = true; 
       } 
      } 
     } 
    } 

現在mCurrentLocation有y我們目前的位置使用它,無論你想要的。

構建從您的onCreate的API客戶端:

// Build the Play services client for use by the Fused Location Provider and the Places API. 
     buildGoogleApiClient(); 
     mGoogleApiClient.connect(); 

,然後你的onResume內:

@Override 
    protected void onResume() { 
     super.onResume(); 
     if (mGoogleApiClient.isConnected()) { 
      getDeviceLocation(); 
     } 
    } 

申報以下全局變量:

// The entry point to Google Play services, used by the Places API and Fused Location Provider. 
    private GoogleApiClient mGoogleApiClient; 
    // A request object to store parameters for requests to the FusedLocationProviderApi. 
    private LocationRequest mLocationRequest; 
    // The desired interval for location updates. Inexact. Updates may be more or less frequent. 
    private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000; 
    // The fastest rate for active location updates. Exact. Updates will never be more frequent 
    // than this value. 
    private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = 
      UPDATE_INTERVAL_IN_MILLISECONDS/2; 
private static final int PERMISSIONS_REQUEST_ACCESS_FINE_LOCATION = 1; 
    private boolean mLocationPermissionGranted; 

    // The geographical location where the device is currently located. 
    private Location mCurrentLocation; 
0

我得到了我的解決方案只稍作修改

String provider; 
    provider=locationManager.getProvider(LocationManager.NETWORK_PROVIDER).getName(); 

      if (Looper.myLooper() == null) { 
       Looper.prepare(); 
      } 

      locationManager.requestSingleUpdate(provider, locationListener, Looper.myLooper()); 

      locationManager.requestLocationUpdates(provider,0,0, locationListener); 

      currentLocation = locationManager.getLastKnownLocation(provider); 
try { 
pDialog.hide();                      
locate = new LatLng(currentLocation.getLatitude(), currentLocation.getLongitude()); 

mMap.clear(); 
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(locate, 13)); 
originMarkers.add(mMap.addMarker(new MarkerOptions() 
     .title("Your Location") 
     .position(locate))); 

origin_lati = "" + currentLocation.getLatitude(); 
origin_longi = "" + currentLocation.getLongitude(); 

Log.e("Lati Longi", origin_lati+", "+origin_longi); 
}catch (Exception e){ 
ActivityCompat.requestPermissions(this, new String[] 
{Manifest.permission.ACCESS_FINE_LOCATION}, 1); 
Log.e("Exception", e.toString()); 
} 
相關問題