Detailed use external storage

Highly recommended article: Welcome Favorite
Android Dry Share

Reading five minutes, ten o'clock daily, lifelong learning with you, here is the Android programmer

This article describes the Androidpart of the development of knowledge by reading this article, you will reap the following:

  1. You need to apply for permission to hold an external storage
  2. External storage use cases (save, read, delete pictures)

AndroidSupport for external memory devices, such as SDcards, save the data in the external storage with global readability, available for reading on a computer such as other equipment and modification. Use external storage needs to gain access to external storage <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />.

1. The need to apply for permission to hold an external storage

This is very important, otherwise inoperable SDcard,

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

2. External storage use cases (save, read, delete pictures)

  • Achieve results

External storage to save the image method

To determine whether to mount the SD card method

    /**
     * 1.判断SD卡是否挂载
     * **/
    public static boolean isMounted() {

        String state = Environment.getExternalStorageState();
        return state.equals(Environment.MEDIA_MOUNTED);

    }
  • SD save pictures, delete pictures, picture display method

Save the picture to SD card

Save the picture to SD card codes are as follows:

    // 保存图片的方法
    public void BtnSaveImage(View view) {
        // 获取图片类型 bitmap
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 将bitmap 压缩成byte类型 并保存到outputstream中
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        bitmap.recycle();
        boolean saveimg = SaveImg(getApplicationContext(), "photo.png",
                baos.toByteArray());
        if (saveimg) {
            Toast.makeText(getApplicationContext(), "保存成功" + store_path,
                    Toast.LENGTH_SHORT).show();
        }
        try {
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 保存图片的方法
    public static boolean SaveImg(Context context, String filename, byte[] data) {
        // 判断是否挂载SD卡
        if (!isMounted()) {
            Toast.makeText(context, "SD卡未安装", Toast.LENGTH_SHORT).show();
            return false;
        }
        File dir = new File(store_path);
        // 创建文件目录
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            // 向文件目录 dir中写文件filename
            FileOutputStream fos = new FileOutputStream(new File(dir, filename));
            fos.write(data);
            fos.close();
            return true;

        } catch (IOException e) {
            e.printStackTrace();
            Log.i("TAG", "IOException..." + e);
            return false;
        }
    }

Deleted images method

To delete a picture code implements the code to achieve the following:

    public void BtnDeleteImage(View view) {
        DeletleImg(getApplicationContext(), "photo.png");

    }

    // 删除图片
    public static void DeletleImg(Context context, String filename) {

        File dirfile = new File(store_path + filename);
        // 判断文件是否存在
        if (!dirfile.exists()) {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        if (dirfile.isDirectory()) {
            String[] childdir = dirfile.list();
            for (int i = 0; i < childdir.length; i++) {
                new File(dirfile, childdir[i]).delete();
            }
        }
        dirfile.delete();
    }

Read picture display method

Display image reading code to achieve the following:

// 读取图片
    public void BtnReadImage(View view) {
        Bitmap readImg = ReadImg(getApplicationContext(), "photo.png");
        if (readImg == null) {
            Toast.makeText(getApplicationContext(), "读取失败" + store_path,
                    Toast.LENGTH_SHORT).show();
        } else {
            ((ImageView) findViewById(R.id.img_external))
                    .setImageBitmap(readImg);
        }

    }

    // 读取图片
    public static Bitmap ReadImg(Context context, String filename) {
        // 判断是否挂载SD卡
        if (!isMounted()) {
            Toast.makeText(context, "SD卡未安装", Toast.LENGTH_SHORT).show();
            return null;
        }
        // 获取文件路径下的文件名称
        File imgFile = new File(store_path, filename);
        if (imgFile.exists()) {
            Log.i("TAG", "imgFile" + imgFile.getAbsolutePath());
            // 将路径下的文件转换成 bitmap
            return BitmapFactory.decodeFile(imgFile.getAbsolutePath());
        } else {
            Toast.makeText(context, "文件不存在", Toast.LENGTH_SHORT).show();
        }

        return null;
    }
  • Layout is as follows:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/img_external"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btn_external_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnSaveImage"
        android:text="保存图片到SD卡" />

    <Button
        android:id="@+id/btn_external_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnDeleteImage"
        android:text="删除SD卡 图片" />

    <Button
        android:id="@+id/btn_external_read"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="BtnReadImage"
        android:text="显示SD卡 图片" />

</LinearLayout>

So far herein, this has ended, if the wrong place, welcome your suggestions and corrections. At the same time look forward to your attention, thank you for reading, thank you!

Micro-channel public concern number: Programmer Android, receive welfare

Guess you like

Origin www.cnblogs.com/wangjie1990/p/11310901.html