How to migrate to Runtime permissions from an older API?

When migrating your Android application to target runtime permissions introduced in Android 6.0 (API level 23), it’s essential to adapt your code to ensure a smooth user experience. Below is a step-by-step guide including code examples to help you transition from the older permission model to the new runtime permissions.

Migration Steps

  1. Update your AndroidManifest.xml file to declare required permissions.
  2. Check if the permission has already been granted at runtime.
  3. If not granted, request the necessary permission from the user.
  4. Handle the permission result in the callback method.

Code Example

<?php // In your Activity class private static final int REQUEST_CODE_PERMISSION = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Check for permission if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // Permission is not granted ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_PERMISSION); } else { // Permission has already been granted accessLocation(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == REQUEST_CODE_PERMISSION) { if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { // Permission granted accessLocation(); } else { // Permission denied Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show(); } } } private void accessLocation() { // Access location data } ?>

Android Migration Runtime Permissions API 23 Android Manifest Request Permissions