Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/192.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 一旦打开“地图”活动,就无法获取当前位置_Java_Android_Google Maps Markers - Fatal编程技术网

Java 一旦打开“地图”活动,就无法获取当前位置

Java 一旦打开“地图”活动,就无法获取当前位置,java,android,google-maps-markers,Java,Android,Google Maps Markers,一旦打开“地图”活动,我就无法获取当前位置。 尽管它用蓝点标记显示当前位置 我看到一条异常消息:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'double android.location.location.getLatitude' 获取坐标需要很多时间。为此,我必须移动我的手机并等待 以下是我的代码: if (Build.VERSION.SDK_INT < 25) { if (ContextCompat.checkSelfP

一旦打开“地图”活动,我就无法获取当前位置。 尽管它用蓝点标记显示当前位置

我看到一条异常消息:java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'double 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());
}

        }
    } 
使用以下命令:

首先创建Google 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;
                }
            }
        }
    }
现在,McCurrentLocation让您的当前位置可以在任何地方使用它

从onCreate生成Api客户端:

// Build the Play services client for use by the Fused Location Provider and the Places API.
        buildGoogleApiClient();
        mGoogleApiClient.connect();
然后在你的简历中:

@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;

我只需稍加修改就得到了我的解决方案

    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());
}

为什么不使用新的fusedLocationApi进行位置更新?我对这个概念很陌生。这是如何工作的?我必须更改完整的代码吗?