无法检索位置Android Marshmallow

时间:2016-05-03 15:50:24

标签: android android-6.0-marshmallow google-api-client

我很难用我的应用程序尝试检索位置。显然我在试图填充位置对象时被卡住了。

Log.d(TAG, "Location changed. New location: " + String.valueOf(mLastlocation.getLatitude()));

试图打电话时

java.lang.RuntimeException: Failure delivering result ResultInfo{who=@android:requestPermissions:, request=0, result=-1, data=Intent { act=android.content.pm.action.REQUEST_PERMISSIONS (has extras) }} to activity {com.myapp/com.myapp.activities.NewsfeedActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference

我收到此错误:((0.05-0.10)/0.05))*100

你知道为什么我无法找回我的位置吗?

提前致谢!

2 个答案:

答案 0 :(得分:0)

尝试此功能,例如:

     LocationManager locationManager;

    locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    List<String> providers = locationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = locationManager.getLastKnownLocation(provider);
        // Log.d("last known location, provider: %s, location: %s", provider, l);
        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            //   Log.d("found best last known location: %s", l);
            bestLocation = l;
        }
    }

    lastKnownLocation = bestLocation;
}

答案 1 :(得分:0)

请参阅这些链接并在运行时添加权限。

https://blog.xamarin.com/requesting-runtime-permissions-in-android-marshmallow/

或尝试这些

创建verifyStoragePermissions()方法并在Activity的onCreateView()中调用

// Declare String array in activity
private static String[] PERMISSIONS_STORAGE = {
       Manifest.Permission.AccessCoarseLocation,
       Manifest.Permission.AccessFineLocation};
public static void verifyStoragePermissions(Activity activity) {
int permission = ActivityCompat.checkSelfPermission(activity,
               Manifest.permission.AccessCoarseLocation);
if (permission != PackageManager.PERMISSION_GRANTED) 
{
        // We don't have permission so prompt the user
        ActivityCompat.requestPermissions(
                activity,
                PERMISSIONS_STORAGE,
                1001  // pass any request code
        );
    }