Every android app runs on its own sandbox. If in needs to access any recourse outside its sandbox, it should request permission from the system. There are few permissions that are automatically granted and there are few permissions that would require user to grant permission. Eg: location,contacts, sms etc.,
All permissions that your app requires should be declared in the manifest file. Devices running Android 5.1(API level 22) and below, would request permission when the user installs the app and devices running Android 6 (API level 23) and above will request permissions when that app tries to use the resource which needs the permission i.e runtime permissions
So lets try a runtime permission sample program.
Step1: Create an android project with an Activity (PermissionActivity.java) and a layout file (activity_permission.xml)
Stept2: Now declare the required permission in the manifest file. This sample program would need SEND_SMS permission and your manifest file should look similar to the one below
Step3: Now lets design the screen with a TextView and a Button. The textview is used to display the current status of the permission and the button is used to request permission if not granted and if granted proceed with the functionality with the acquired permission
activity_permission.xml:
Step4: Now in the Activity, bind the UI components (TextView & Button). On click of the button request for SMS permission and proceed with the permission acquired.
PermissionActivity.java:
On click of the button, we would check if the API version is 23 & above then we should check if the app has the permission or not using checkSelfPermission method. If not request the user for the permission at runtime using ActivityCompat.requestPermissions.
During the permission request user may select Never ask again option and deny the permission. In such case, use the shouldShowRequestPremissionRationale which would be false, to determine whether to show an alternative explanation to user and direct him to setting menu or not.
For all actions performed by the user in the runtime permission request dialog, we would receive a callback in the onRequestPermissionResult method.
Step5: Run the app in an emulator or device with Android API level 23 or above. Click on the Send SMS button. System would prompt a dialog requesting a runtime permission to send sms from you app.
Output: