Reputation: 1213
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?
Upvotes: 1
Views: 3369
Reputation: 1213
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:
Upvotes: 2