【问题标题】:Getting Error and App crash When I try to Access current location当我尝试访问当前位置时出现错误和应用程序崩溃
【发布时间】:2019-04-17 08:43:13
【问题描述】:
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)

【问题讨论】:

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

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


【解决方案1】:

首先在你的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(Location 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);
}

你准备好了!!!! 干杯快乐编码

【讨论】:

    【解决方案2】:

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

       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" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-22
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多