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

Java 尝试访问当前位置时出现错误和应用程序崩溃,java,android,google-maps-api-3,Java,Android,Google Maps Api 3,错误: E/AndroidRuntime:致命异常:主 进程:com.uws.pnai.mapsapi,PID:15830 java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“double android.location.location.getLatitude” 在com.uws.pnai.mapsapi.MapActivity$1.onCompleteMapActivity.java:77 位于com.google.android.gms.tasks

错误: E/AndroidRuntime:致命异常:主 进程:com.uws.pnai.mapsapi,PID:15830 java.lang.NullPointerException:尝试对空对象引用调用虚拟方法“double android.location.location.getLatitude” 在com.uws.pnai.mapsapi.MapActivity$1.onCompleteMapActivity.java:77 位于com.google.android.gms.tasks.zzf.run未知源 位于android.os.Handler.handleCallbackHandler.java:751 在android.os.Handler.dispatchMessageHandler.java:95 在android.os.Looper.Looper.java:154 在android.app.ActivityThread.mainActivityThread.java:6780 在java.lang.reflect.Method.Invokenactive方法中 在com.android.internal.os.ZygoteInit$MethodAndArgsCaller.runZygoteInit.java:1500
在com.android.internal.os.ZygoteInit.mainZygoteInit.java:1390

中,首先在build.gradle文件中添加此实现

在该实现之后,在活动或片段中实现LocationListener,然后实现其功能,然后

在onCreate getLocation中调用此方法; 然后在这个函数中添加这些行

compile 'com.google.android.gms:play-services-location:11.2.0'
之后在您的onLocationChangedLocation位置 添加这些代码行

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....
        //.................
    }
}
你已经准备好了!!!!
干杯快乐编码

如果您想要持续的位置更新,您可以使用后台服务。下面的代码用于位置服务

@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);
}
在MainActivity中调用此服务,如下所示

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

使用位置=首先检查是否未崩溃,请在清单文件中添加访问精细和粗略位置权限,如果您完成了所有操作,请尝试一个简单的打开谷歌地图应用程序,然后它会要求启用位置,然后启动您的应用程序,您将获得位置非空,getLastLocation可能返回null,因为设备/操作系统不会自动保持最后一个位置可用。如果您确实需要最新的位置,请请求位置更新。这是一个非常常见的问题,实际上是一个功能,已经包含在几个StackOverflow问题和答案中,但我不知道哪一个最好链接到这里。
   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);
                }
            }
    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" />