Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import android.content.Context;

import android.os.Environment;

import android.os.storage.StorageManager;

import java.lang.reflect.Array;
import java.lang.reflect.Method;

public class Main {
    public static String BASE_DIR = null;

    public static String getAvailableStoragePath(Context context) {
        if (BASE_DIR == null) {
            try {
                BASE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
                StorageManager sStorageManager = (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);

                Class<?> smClazz = sStorageManager.getClass();
                Method listMethod = smClazz.getDeclaredMethod("getVolumeList");
                Object vlObject = listMethod.invoke(sStorageManager);

                if (vlObject.getClass().isArray()) {
                    String state = null;
                    String path = null;
                    // Class svClazz =
                    // Class.forName("android.os.storage.StorageVolume");
                    Object svObject = Array.get(vlObject, 1);
                    if (svObject != null) {
                        Method pathMethod = svObject.getClass().getMethod("getPath");
                        path = (String) pathMethod.invoke(svObject);

                        Method stateMethod = smClazz.getMethod("getVolumeState", new Class[] { String.class });
                        state = (String) stateMethod.invoke(sStorageManager, path);
                    }

                    if (path != null && state != null && state.equals(Environment.MEDIA_MOUNTED)) {
                        BASE_DIR = path;
                    } else {
                        BASE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
                    }
                }
            } catch (Exception e) {
                BASE_DIR = Environment.getExternalStorageDirectory().getAbsolutePath();
            }

            return BASE_DIR;
        } else {
            return BASE_DIR;
        }

    }
}