Android media viewer read permission
Introduction
The Android media viewer read permission tutorial series describes how to implement permission to access external read storage for both marshmallow devices and older.
Get Code
The code can be found on github from the following instructions below
https://github.com/mobapptuts/media-thumbnail-viewer.git Tag
media-viewer-permissions
or you can run this command
git clone https://github.com/mobapptuts/media-thumbnail-viewer.git –branch
media-viewer-permissions
This video describes how to import a project from github using android studio and also how to select a git tag.
Steps
Create a new android project
Add the external read storage permission to the AndroidManifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
Create a request id member to represent the read external storage permission request
private final static int READ_EXTERNAL_STORAGE_PERMMISSION_RESULT = 0;
Create a method to check whether the read external storage runtime permission has been granted or not
private void checkReadExternalStoragePermission() { if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if(ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { // Start cursor loader } else { if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)) { Toast.makeText(this, "App needs to view thumbnails", Toast.LENGTH_SHORT).show(); } requestPermissions(new String[] {Manifest.permission.READ_EXTERNAL_STORAGE}, READ_EXTERNAL_STORAGE_PERMMISSION_RESULT); } } else { // Start cursor loader } }
Implement the onRequestPermissionsResult method to check whether the external read storage request has been granted
@Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { switch(requestCode) { case READ_EXTERNAL_STORAGE_PERMMISSION_RESULT: if(grantResults[0] == PackageManager.PERMISSION_GRANTED) { //Call cursor loader Toast.makeText(this, "Now have access to view thumbs", Toast.LENGTH_SHORT).show(); } break; default: super.onRequestPermissionsResult(requestCode, permissions, grantResults); } }
Call the checkReadExternalStoragePermission method from onCreate
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_media_viewer_main); checkReadExternalStoragePermission(); }
Android media viewer read permission summary
A logical start to android application development is to ensure you have the correct permissions setup for any resources that your app will need.
In this case the android media thumbnail viewer requires access for reading files from storage.
So as well as providing the appropriate permission in the AndroidManifest file, runtime permissions were also setup in the main activity.