码迷,mamicode.com
首页 > 移动开发 > 详细

Android API之ExternalStorage操作

时间:2016-07-21 11:04:42      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:

官方API文档:
https://developer.android.com/guide/topics/sensors/sensors_environment.html
https://developer.android.com/reference/android/os/Environment.html

/**
 * Android中外存储设备(SD卡)操作
 * 
 * @description:
 * @author ldm
 * @date 2016-7-21 上午9:33:53
 */
public class ExternalStorage extends Activity {
    // 装载控件的容器
    private ViewGroup container;
    /**
     * Android的外部存储,在APILevel=8之前,所有的文件都是建议放在Environment.getExternalStorageState()目录下的。
     * 从API Level=8开始,对于应用程序的私有文件应该放在Context.getExternalFilesDir目录下。
     * 非私有的(shared)的文件应该放在目录下Environment.getExternalStoragePublicDirectory(String)所指定的目录下。
     * 私有的文件放在Environment.getExternalStorageDirectory()所指定的目录下。
     */
    // 非私有图片
    private Item mExternalStoragePublicPicture;
    // 私有图片
    private Item mExternalStoragePrivatePicture;
    // 私有文件
    private Item mExternalStoragePrivateFile;
    // 处存储设备文件扫描广播
    private BroadcastReceiver mExternalStorageReceiver;
    // 外存储是否可用
    boolean mExternalStorageAvailable = false;
    // 外存储是否可写操作
    boolean mExternalStorageWriteable = false;

    // 自定义的Item
    static class Item {
        View mRoot;
        // 创建文件的Button
        Button mCreate;
        // 删除文件Button
        Button mDelete;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.external_storage);
        initViews();
        addViewsToContainer();
        startWatchingExternalStorage();
    }

    /**
     * 给ViewGroup添加View
     * 
     * @description:
     * @author ldm
     * @date 2016-7-21 上午9:06:33
     */
    private void addViewsToContainer() {
        mExternalStoragePublicPicture = createStorageControls(
                "Picture: getExternalStoragePublicDirectory",
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                new View.OnClickListener() {
                    public void onClick(View v) {
                        createExternalStoragePublicPicture();
                        updateExternalStorageState();
                    }
                }, new View.OnClickListener() {
                    public void onClick(View v) {
                        deleteExternalStoragePublicPicture();
                        updateExternalStorageState();
                    }
                });
        container.addView(mExternalStoragePublicPicture.mRoot);
        mExternalStoragePrivatePicture = createStorageControls(
                "Picture getExternalFilesDir",
                getExternalFilesDir(Environment.DIRECTORY_PICTURES),
                new View.OnClickListener() {
                    public void onClick(View v) {
                        createExternalStoragePrivatePicture();
                        updateExternalStorageState();
                    }
                }, new View.OnClickListener() {
                    public void onClick(View v) {
                        deleteExternalStoragePrivatePicture();
                        updateExternalStorageState();
                    }
                });
        container.addView(mExternalStoragePrivatePicture.mRoot);
        mExternalStoragePrivateFile = createStorageControls(
                "File getExternalFilesDir", getExternalFilesDir(null),
                new View.OnClickListener() {
                    public void onClick(View v) {
                        createExternalStoragePrivateFile();
                        updateExternalStorageState();
                    }
                }, new View.OnClickListener() {
                    public void onClick(View v) {
                        deleteExternalStoragePrivateFile();
                        updateExternalStorageState();
                    }
                });
        container.addView(mExternalStoragePrivateFile.mRoot);
    }

    private void initViews() {
        container = (ViewGroup) findViewById(R.id.container);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopWatchingExternalStorage();
    }

    private void handleExternalStorageState(boolean available, boolean writeable) {
        boolean has = hasExternalStoragePublicPicture();
        mExternalStoragePublicPicture.mCreate.setEnabled(writeable && !has);
        mExternalStoragePublicPicture.mDelete.setEnabled(writeable && has);
        has = hasExternalStoragePrivatePicture();
        mExternalStoragePrivatePicture.mCreate.setEnabled(writeable && !has);
        mExternalStoragePrivatePicture.mDelete.setEnabled(writeable && has);
        has = hasExternalStoragePrivateFile();
        mExternalStoragePrivateFile.mCreate.setEnabled(writeable && !has);
        mExternalStoragePrivateFile.mDelete.setEnabled(writeable && has);
    }

    private void updateExternalStorageState() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        handleExternalStorageState(mExternalStorageAvailable,
                mExternalStorageWriteable);
    }

    private void startWatchingExternalStorage() {
        mExternalStorageReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                updateExternalStorageState();
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_REMOVED);
        registerReceiver(mExternalStorageReceiver, filter);
        updateExternalStorageState();
    }

    private void stopWatchingExternalStorage() {
        unregisterReceiver(mExternalStorageReceiver);
    }

    // 创建外存储中公共图片
    private void createExternalStoragePublicPicture() {

        File path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path, "DemoPicture.jpg");

        try {
            path.mkdirs();
            InputStream is = getResources()
                    .openRawResource(R.drawable.balloons);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            // 媒体文件进行扫描,看是否有新文件,使得MediaProvider同步媒体数据库
            // scanFile(Context context, String[] paths, String[] mimeTypes,
            // OnScanCompletedListener callback)
            // 传入参数分别是上下文对象,文件路径对应的数组,文件类型及扫描监听
            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            Log.i("ExternalStorage", "Scanned " + path + ":");
                            Log.i("ExternalStorage", "-> uri=" + uri);
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 删除外存储中是否有指定的公共图片
    private void deleteExternalStoragePublicPicture() {

        File path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path, "DemoPicture.jpg");
        file.delete();
    }

    // 判断外存储中是否有指定的公共图片
    private boolean hasExternalStoragePublicPicture() {
        File path = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
        File file = new File(path, "DemoPicture.jpg");
        return file.exists();
    }

    // 在外存储中创建私有文件
    private void createExternalStoragePrivatePicture() {
        // 创建文件
        File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File file = new File(path, "DemoPicture.jpg");

        try {

            InputStream is = getResources()
                    .openRawResource(R.drawable.balloons);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();

            // 媒体文件进行扫描,看是否有新文件,使得MediaProvider同步媒体数据库
            // scanFile(Context context, String[] paths, String[] mimeTypes,
            // OnScanCompletedListener callback)
            // 传入参数分别是上下文对象,文件路径对应的数组,文件类型及扫描监听
            MediaScannerConnection.scanFile(this,
                    new String[] { file.toString() }, null,
                    new MediaScannerConnection.OnScanCompletedListener() {
                        public void onScanCompleted(String path, Uri uri) {
                            // 扫描完成后处理
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 删除外存储中指定的私有图片
    private void deleteExternalStoragePrivatePicture() {
        File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (path != null) {
            File file = new File(path, "DemoPicture.jpg");
            file.delete();
        }
    }

    // 判断是否有指定的图片
    private boolean hasExternalStoragePrivatePicture() {
        File path = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        if (path != null) {
            File file = new File(path, "DemoPicture.jpg");
            return file.exists();
        }
        return false;
    }
    //在外存储中创建私有文件
    private void createExternalStoragePrivateFile() {
        File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
        try {
            InputStream is = getResources()
                    .openRawResource(R.drawable.balloons);
            OutputStream os = new FileOutputStream(file);
            byte[] data = new byte[is.available()];
            is.read(data);
            os.write(data);
            is.close();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void deleteExternalStoragePrivateFile() {
        // 获取外部存储文件的路径。如果文件存在则删除
        File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
        if (file != null) {
            file.delete();
        }
    }

    private boolean hasExternalStoragePrivateFile() {
        // 获取外部存储文件的路径。如果文件不存在,则返lse
        File file = new File(getExternalFilesDir(null), "DemoFile.jpg");
        return (file != null) && file.exists();
    }

    /**
     * 
     * @description:创建Item对View
     * @author ldm
     * @date 2016-7-21 上午9:08:00
     */
    private Item createStorageControls(CharSequence label, File path,
            View.OnClickListener createClick, View.OnClickListener deleteClick) {
        // 获取系统LayoutInflater
        LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        // 始化Item
        Item item = new Item();
        item.mRoot = inflater.inflate(R.layout.external_storage_item, null);
        TextView tv = (TextView) item.mRoot.findViewById(R.id.label);
        tv.setText(label);
        if (path != null) {
            tv = (TextView) item.mRoot.findViewById(R.id.path);
            tv.setText(path.toString());
        }
        // 初始化Button及点击事件
        item.mCreate = (Button) item.mRoot.findViewById(R.id.create);
        item.mCreate.setOnClickListener(createClick);
        item.mDelete = (Button) item.mRoot.findViewById(R.id.delete);
        item.mDelete.setOnClickListener(deleteClick);
        return item;
    }
}

—-布局文件——

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:scrollbars="none" >

    <LinearLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>

</ScrollView>

Android API之ExternalStorage操作

标签:

原文地址:http://blog.csdn.net/true100/article/details/51979658

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!