from api level 23 (android 6.0 marshmallow) we need to ask run-time permission from the user-end. you can do this in two steps.
1) add these two permissions in androidmanifest.xml file.
androidmanifest.xml
<uses-permission android:name="android.permission.access_fine_location"/>
<uses-permission android:name="android.permission.access_coarse_location"/>
example:
<manifest xlmns:android...> ... <uses-permission android:name="android.permission.access_fine_location" /> <uses-permission android:name="android.permission.access_coarse_location" /> <application ... </manifest>
2) put this code block inside class where you need to get current location
if ( build.version.sdk_int >= 23){ if (activitycompat.checkselfpermission(this, android.manifest.permission.access_fine_location) != packagemanager.permission_granted ){ requestpermissions(new string[]{ android.manifest.permission.access_fine_location}, request_code_ask_permissions); return ; } } getlocation(); } //get access to location permission final private int request_code_ask_permissions = 123; @override public void onrequestpermissionsresult(int requestcode, string[] permissions, int[] grantresults) { switch (requestcode) { case request_code_ask_permissions: if (grantresults[0] == packagemanager.permission_granted) { getlocation(); } else { // permission denied toast.maketext( this,"your message" , toast.length_short) .show(); } break; default: super.onrequestpermissionsresult(requestcode, permissions, grantresults); } } //get location public void getlocation(){ locationmanager locationmanager = (locationmanager) getsystemservice(location_service); location mylocation=locationmanager.getlastknownlocation(locationmanager.gps_provider); if (mylocation == null) { mylocation = locationmanager.getlastknownlocation(locationmanager.passive_provider); } }
from api level 23 (android 6.0 marshmallow) we need to ask run-time permission from the user-end. you can do this in two steps.
1) add these two permissions in
androidmanifest.xml
file.<uses-permission android:name="android.permission.access_fine_location"/>
<uses-permission android:name="android.permission.access_coarse_location"/>
example:
2) put this code block inside class where you need to get current location