Android - Google地图为位置返回null [重复]

【Android - Google地图为位置返回null [重复]】风流不在谈锋胜,袖手无言味最长。这篇文章主要讲述Android - Google地图为位置返回null [重复]相关的知识,希望能为你提供帮助。
这个问题在这里已有答案:

  • getLastKnownLocation() returns null [closed] 1回答
我需要在日志中看到我的位置,频率为0.1秒。
mMap.setMyLocationEnabled(true); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); for (int i = 1; i < 100; i++) new Handler().postDelayed(new Runnable() { @Override public void run() { if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED & & ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // TODO: Consider calling //ActivityCompat#requestPermissions // here to request the missing permissions, and then overriding //public void onRequestPermissionsResult(int requestCode, String[] permissions, //int[] grantResults) // to handle the case where the user grants the permission. See the documentation // for ActivityCompat#requestPermissions for more details. return; } mMap.setMyLocationEnabled(true); LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); final Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false)); Log.d("Coordinates: ",location.getLongitude() + "," + location.getLatitude()); } }, 100 * i);

我通过模拟器看到日志中的坐标,但是当我通过USB连接手机时,我遇到了Log.d()线路崩溃,出现以下错误:
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLongitude()' on a null object reference

答案当找不到先前记录的位置或者找到之前的位置是很久以前并且它的gps数据到期时,最后一个已知位置可以为空。
如果找到的最后一个位置为null,则可以使用融合位置提供程序API并查找位置。你将在onLocationChanged回调中获取它。

    推荐阅读