I'm currently trying to get the latitude and longitude of the user's current location. I have included the following permissions in the manifest. TargetSDK and min sdk - 23
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.name.app"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:smallScreens="false" /> <activity android:name=".SplashScreen" android:screenOrientation="portrait"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".MainMenu" /> <activity android:name=".NeedToKnow" /> <activity android:name=".SelectTopic" /> <activity android:name=".DisplayTopicInformation"/> <activity android:name=".SelectCheckList" /> <activity android:name=".ViewCheckList"/> <activity android:name=".FindLocation"></activity> </application> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> </manifest>
For this, I understand that I need to run a runtime check for permissions. However, when I do the following, I always get -1 in return. (PERMISSION_DENIED)
int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION);
Is there any step that I skip when trying to access current locations?
The full code is here:
private String getZipcodeFromCurrentLocation() { int permissionCheck = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION); String zip = null; Location location = null; LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE); LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { latitude = location.getLatitude(); longitude = location.getLongitude(); Log.i("updated lat", String.valueOf(latitude)); Log.i("updated lng", String.valueOf(longitude)); } }; try { if (PackageManager.PERMISSION_GRANTED == permissionCheck) { lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener); } } catch (SecurityException e){ e.printStackTrace(); } return zip; }
source share