尝试访问当前位置时出现错误和应用程序崩溃

时间:2018-11-14 11:33:12

标签: java android google-maps-api-3

public void onMapReady(GoogleMap googleMap) {
        Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
        Log.d(TAG, "onMapReady: map is ready");
        mMap = googleMap;

        if (mLocationPermissionsGranted) {
            getDeviceLocation();
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
            mMap.setBuildingsEnabled(true);
            mMap.getUiSettings().setMyLocationButtonEnabled(false);
        }
    }

 private void getDeviceLocation() {
        Log.d(TAG, "getDeviceLocation: Getting the current location");

        mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);

        try {
            if (mLocationPermissionsGranted) {
                final com.google.android.gms.tasks.Task<Location> location = mFusedLocationProviderClient.getLastLocation();
                location.addOnCompleteListener(new OnCompleteListener<Location>() {
                    @Override
                    public void onComplete(@NonNull com.google.android.gms.tasks.Task<Location> task) {
                        if(task.isSuccessful()){
                            Log.d(TAG, "onComplete: found Location");
                            Location currentLocation = (Location) task.getResult();

                            moveCamera(new LatLng(currentLocation.getLatitude() ,currentLocation.getLongitude()),DEFAULT_ZOOM);
                        }else{
                            Log.d(TAG, "onComplete: current location is null");
                            Toast.makeText(MapActivity.this,"Unable to get current location", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

        } catch (SecurityException e) {
            Log.e(TAG, "getDeviceLocation: SecurityException " + e.getMessage());
        }
    }

错误: E / AndroidRuntime:致命异常:main     流程:com.uws.pnai.mapsapi,PID:15830     java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法'double android.location.Location.getLatitude()'         在com.uws.pnai.mapsapi.MapActivity $ 1.onComplete(MapActivity.java:77)         com.google.android.gms.tasks.zzf.run(未知来源)         在android.os.Handler.handleCallback(Handler.java:751)         在android.os.Handler.dispatchMessage(Handler.java:95)         在android.os.Looper.loop(Looper.java:154)         在android.app.ActivityThread.main(ActivityThread.java:6780)         在java.lang.reflect.Method.invoke(本机方法)         在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:1500)         在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1390)

2 个答案:

答案 0 :(得分:0)

首先将此实现添加到您的build.gradle文件中

compile 'com.google.android.gms:play-services-location:11.2.0'

在实现之后,在您的活动或片段中实现(实现LocationListener),然后在实现其功能之后,然后

在您的onCreate() getLocation();中调用此方法 然后在此函数中添加这些行

protected void getLocation() {
    if (isLocationEnabled(MainActivity.this)) {
        locationManager = (LocationManager)  this.getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();

        //You can still do this if you like, you might get lucky:
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            Log.e("TAG", "GPS is on");
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
            searchNearestPlace(voice2text);
        }
        else{
            //This is what you need:
            locationManager.requestLocationUpdates(bestProvider, 1000, 0, this);
        }
    }
    else
    {
        //prompt user to enable location....
        //.................
    }
}

之后,在您的onLocationChanged(位置位置)中 添加这些代码行

@Override
public void onLocationChanged(Location location) {
    //Hey, a non null location! Sweet!

    //remove location callback:
    locationManager.removeUpdates(this);

    //open the map:
    latitude = location.getLatitude();
    longitude = location.getLongitude();
    Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
    searchNearestPlace(voice2text);
}

您就可以出发了!!!! 欢呼快乐编码

答案 1 :(得分:-1)

如果要连续更新位置,可以使用后台服务。以下代码用于位置服务

   public class LocationTracking  extends Service {
            private static final String TAG = "BOOMBOOMTESTGPS";
            private LocationManager mLocationManager = null;
            private static final int LOCATION_INTERVAL = 10000;
            private static final float LOCATION_DISTANCE = 0;
            double latitude; // latitude
            double longitude; // longitude
            String emp_id=Login.strUserID;;
            View view;
            private class LocationListener implements android.location.LocationListener
            {
                Location mLastLocation;

                public LocationListener(String provider)
                {
                    Log.e(TAG, "LocationListener " + provider);
                    mLastLocation = new Location(provider);
                }

                @Override
                public void onLocationChanged(Location location)
                {
                    ConnectivityManager cn = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo nf = cn.getActiveNetworkInfo();
                    if (nf != null && nf.isConnected() == true) {
                        Log.e(TAG, "onLocationChanged: " + location);
                        latitude=location.getLatitude();
                        longitude=location.getLongitude();
                        SendQueryString(latitude,longitude);
                        Log.d("tag","lat"+latitude+"Long"+longitude+"");
                         Toast.makeText(LocationTracking.this,"Lat and Long"+location+"emp_id"+emp_id+"",Toast.LENGTH_LONG).show();
                        mLastLocation.set(location);

                    }else{
                        Toast.makeText(LocationTracking.this,"Bad network",Toast.LENGTH_LONG).show();
                        showErrorToast(view);
                   }
                }

                public void showErrorToast(View view) {
                    MDToast.makeText(LocationTracking.this, "Bad Network Connection", MDToast.LENGTH_LONG, MDToast.TYPE_ERROR);
                }

                @Override
                public void onProviderDisabled(String provider)
                {
                    Log.e(TAG, "onProviderDisabled: " + provider);
                }

                @Override
                public void onProviderEnabled(String provider)
                {
                    Log.e(TAG, "onProviderEnabled: " + provider);
                }

                @Override
                public void onStatusChanged(String provider, int status, Bundle extras)
                {
                    Log.e(TAG, "onStatusChanged: " + provider);
                }
            }

            LocationListener[] mLocationListeners = new LocationListener[] {
                    new LocationListener(LocationManager.GPS_PROVIDER),
                    //new LocationListener(LocationManager.NETWORK_PROVIDER)
            };

            @Override
            public IBinder onBind(Intent arg0)
            {
                return null;
            }

            @Override
            public int onStartCommand(Intent intent, int flags, int startId)
            {
                Log.e(TAG, "onStartCommand");
                super.onStartCommand(intent, flags, startId);
                return START_STICKY;
            }

            @Override
            public void onCreate()
            {
                Log.e(TAG, "onCreate");
                initializeLocationManager();
               /* try {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                            mLocationListeners[1]);
                } catch (java.lang.SecurityException ex) {
                    Log.i(TAG, "fail to request location update, ignore", ex);
                } catch (IllegalArgumentException ex) {
                    Log.d(TAG, "network provider does not exist, " + ex.getMessage());
                }*/
                try {
                    mLocationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                            mLocationListeners[0]);
                } catch (java.lang.SecurityException ex) {
                    Log.i(TAG, "fail to request location update, ignore", ex);
                } catch (IllegalArgumentException ex) {
                    Log.d(TAG, "gps provider does not exist " + ex.getMessage());
                }
            }

            @Override
            public void onDestroy()
            {
                Log.e(TAG, "onDestroy");
                super.onDestroy();
                if (mLocationManager != null) {
                    for (int i = 0; i < mLocationListeners.length; i++) {
                        try {
                            mLocationManager.removeUpdates(mLocationListeners[i]);
                        } catch (Exception ex) {
                            Log.i(TAG, "fail to remove location listners, ignore", ex);
                        }
                    }
                }
            }

            private void initializeLocationManager() {
                Log.e(TAG, "initializeLocationManager");
                if (mLocationManager == null) {
                    mLocationManager = (LocationManager)getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
                }
            }

像这样在MainActivity中调用此服务

    try {
            startService(new Intent(RegularCustomerBilling.this, LocationTracking.class));
        } catch (Exception e) {

        }




And in manifest mention that service

             <service
                        android:name=".LocationTracking"
                        android:enabled="true"
                        android:exported="true" />