How to invoke the checkSelfPermission method from Android API 22 and bellow
I build android apps using NetBeans and the NBDroid plugin. I don't use Gradle and AppCompat framework so sometimes I have to "hack" a few things.
Recently I had to make an app that needs access to the coarse location of the user. The app is written for Android API 19 (Android 4.4.2) so I added the android.permission.ACCESS_COARSE_LOCATION permission to the manifest.xml and everything was fine until a few people installed it on their Android 6 phone.
Well... in Android 6 (API 23) the permission system is bit different. The API 23 has a new featured called "Requesting Permissions at Run Time" so if you need to have access to coarse or fine location then you have to call the checkSelfPermissions method.
I spent my whole evening trying to figure out how I can make my API 19 android app to call the checkSelfPermissions method if someone installs it on an Android API 23. After a very long evening I finally managed to make it and I decided to share it with you.
Hope you find it useful!
I spent my whole evening trying to figure out how I can make my API 19 android app to call the checkSelfPermissions method if someone installs it on an Android API 23. After a very long evening I finally managed to make it and I decided to share it with you.
Hope you find it useful!
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CheckForCoarseLocationPermission(); } private void CheckForCoarseLocationPermission() { if (android.os.Build.VERSION.SDK_INT >= 23) { // ANDROID 6.0 AND UP! boolean accessCoarseLocationAllowed = false; try { // Invoke checkSelfPermission method from Android 6 (API 23 and UP) java.lang.reflect.Method methodCheckPermission = Activity.class.getMethod("checkSelfPermission", java.lang.String.class); Object resultObj = methodCheckPermission.invoke(this, Manifest.permission.ACCESS_COARSE_LOCATION); int result = Integer.parseInt(resultObj.toString()); if (result == PackageManager.PERMISSION_GRANTED) { accessCoarseLocationAllowed = true; } } catch (Exception ex) { } if (accessCoarseLocationAllowed) { return; } try { // We have to invoke the method "void requestPermissions (Activity activity, String[] permissions, int requestCode) " // from android 6 java.lang.reflect.Method methodRequestPermission = Activity.class.getMethod("requestPermissions", java.lang.String[].class, int.class); methodRequestPermission.invoke(this, new String[] { Manifest.permission.ACCESS_COARSE_LOCATION }, 0x12345); } catch (Exception ex) { } } }