Saturday, August 26, 2017

android - Get musics list only from sd card

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    android:orientation="vertical"
    android:background="#bde295"
    >
    <ListView
        android:id="@+id/list_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        />
</LinearLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;

import java.util.HashMap;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private LinearLayout mRootLayout;
    private ListView mListView;

    private static final int MY_PERMISSION_REQUEST_CODE = 123;

    private HashMap<Long,String> mAudioMap = new HashMap<>();


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        mActivity = MainActivity.this;

        // Get the widget reference from xml layout
        mRootLayout = findViewById(R.id.root_layout);
        mListView = findViewById(R.id.list_view);

        // Custom method to check permission at run time
        checkPermission();
    }

    // Custom method to get all audio files list from external storage
    protected void getMusicFilesList(){
        // Get the content resolver
        ContentResolver contentResolver = mContext.getContentResolver();

        // Get the external storage uri of media store audio
        Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;

        /*
            String IS_MUSIC
                Non-zero if the audio file is music

            Type: INTEGER (boolean)
        */

        // Query string to filter music files only
        // Remove ringtone, notification etc sound from the list
        String selectionString = MediaStore.Audio.Media.IS_MUSIC + "!=0";

        // Query string to sort musics by date added
        String sortString = MediaStore.Audio.Media.DATE_ADDED;

        // Query the media store for music files only
        Cursor cursor = contentResolver.query(
                uri, // Uri
                null, // Projection
                selectionString, // Selection
                null, // Selection args
                sortString // Sort order
        );

        if (cursor == null) {
            // Query failed, handle error
        } else if (!cursor.moveToFirst()) {
            // No media on the device
        } else {
            int title = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
            int id = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
            // Loop through the musics
            do {
                // Get the current audio file id
                long thisId = cursor.getLong(id);

                // Get the current audio title
                String thisTitle = cursor.getString(title);

                // Process current music here
                mAudioMap.put(thisId,thisTitle);
            } while (cursor.moveToNext());
        }

        // Get the values array from hash map
        String[] titlesArray = mAudioMap.values().toArray(new String[mAudioMap.size()]);

        // Initialize an array adapter
        ArrayAdapter adapter = new ArrayAdapter(
                mContext, // Context
                android.R.layout.simple_list_item_1, // Item layout
                titlesArray // Data source
        );
        // Data bind list view with array adapter
        mListView.setAdapter(adapter);
    }

    // Custom method to check and grant permission at run time
    protected void checkPermission(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M){
            if(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){
                if(shouldShowRequestPermissionRationale(Manifest.permission.READ_EXTERNAL_STORAGE)){
                    // Show an alert dialog
                    AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
                    builder.setMessage("Read external storage permission is required.");
                    builder.setTitle("Please grant permission");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ActivityCompat.requestPermissions(
                                    mActivity,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                    MY_PERMISSION_REQUEST_CODE
                            );
                        }
                    });
                    builder.setNeutralButton("Cancel",null);
                    AlertDialog dialog = builder.create();
                    dialog.show();
                }else {
                    // Request permission
                    ActivityCompat.requestPermissions(
                            mActivity,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSION_REQUEST_CODE
                    );
                }
            }else {
                // Permission already granted
                getMusicFilesList();
            }
        }else {
            // Permission granted by manifest file
            getMusicFilesList();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults){
        switch(requestCode){
            case MY_PERMISSION_REQUEST_CODE:{
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    // Permission granted
                    getMusicFilesList();
                }else {
                    // Permission denied
                }
            }
        }
    }
}
AndroidManifest.xml [Permission]

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>