Why does locationManager.getBestProvider() returns null? (Nexus 5x)

好久不见. 提交于 2019-12-08 03:33:04

问题


I am trying to get device (Nexus 5x) location by following a tutorial. But its not working and I found out, that the line

locationManager.getBestProvider(new Criteria(), false);

always returns null.

Here is my manifest content:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="lt.wilkas.locationdemo">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Here is my onCreate content:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize location manager
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        //get best provider
        provider = locationManager.getBestProvider(new Criteria(), false);

        if (provider == null) {
            Log.i("i", "provider ir null");
        } else {
            Log.i("i", provider);
        }
}

What am I doing not right?


回答1:


There are two ways to solve this issue.

1) One could update the value of targetSdkVersion to lower than 23 in a file "build.gradle". Thanks to Beyka.

2) Since Android 6.0 "dangerous" permissions should not only be included in the manifest file, but also asked for confirmation while App is running (Requesting Permissions at Run Time). Location provider should be asked only after getting runtime permission from the user. Thanks to Prerak Sola.

These are great resources and examples how to do that:

  • https://developer.android.com/training/permissions/requesting.html
  • https://github.com/googlesamples/android-RuntimePermissions/blob/master/Application/src/main/java/com/example/android/system/runtimepermissions/MainActivity.java


来源:https://stackoverflow.com/questions/38696068/why-does-locationmanager-getbestprovider-returns-null-nexus-5x

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!