zoukankan      html  css  js  c++  java
  • 【幻化万千戏红尘】qianfeng-Android-Day12SharedPreference、内部存储、外部存储

    Android数据存储——SharedPreferencesSDCard

    一、数据存储选项:Data Storage ——Storage Options【重点】

    1Shared Preferences

    Store private primitive data in key-value pairs.

    保存简单的键值对数据。

    2Internal Storage

    Store private data on the device memory.

    在手机内存中保存不对外共享的信息。

    3External Storage

    Store public data on the shared external storage.

    在外部存储设备上保存公共的数据信息。主要指保存在SDCard上。

    4SQLite Databases

    Store structured data in a private database.

    将结构化的数据保存进数据库。

    5Network Connection

    Store data on the web with your own network server.

    将数据保存到自己的远程服务器上。

    【备注:】

    • 内部存储空间十分有限,因而显得可贵,另外,它也是系统本身和系统应用程序主要的数据存储所在地,一旦内部存储空间耗尽,手机也就无法使用了。 
    • 所以对于内部存储空间,我们要尽量避免使用。Shared Preferences和SQLite数据库都是存储在内部存储空间上的。内部存储一般用Context来获取和操作。 
    • getFilesDir()获取你app的内部存储空间,相当于你的应用在内部存储上的根目录。
    • 最容易混淆的是外部存储,如果说pc上区分出外部存储和内部存储的话,那么自带的硬盘算是内部存储,U盘或者移动硬盘算是外部存储,因此我们很容易带着这样的理解去看待安卓手机,认为机身固有存储是内部存储,而扩展的SDCard卡是外部存储。比如Nexus 4有16G的内部存储,普通消费者可以这样理解,但是安卓的编程中不能,这16GB仍然是外部存储。

    二、SharedPreferences:

    (一)、概念:

        SharedPreferencesAndroid系统提供的一个通用的数据持久化框架,用于存储和读取key-value类型的原始基本数据类型对,目前支持stringintlongfloatboolean基本类型的存储,对于自定义的对象数据类型,无法使用SharedPreferences来存储。

            SharedPreferences主要用于存储系统的配置信息。例如上次登录的用户名,上次最后设置的配置信息(如:是否打开音效、是否使用振动,小游戏的玩家积分等)。当再次启动程序后依然保持原有设置。SharedPreferences用键值对方式存储,方便写入和读取。

    (二)、使用SharedPreferences的步骤

    1、获取SharedPreferences对象;

            SharedPreferences本身是一个接口,无法直接创建实例,通过ContextgetSharedPreferences(String name, int  mode)方法来获取实例。

            该方法的第二个参数有以下三个值:【文件读写的操作模式

    • Context.MODE_PRIVATE:  指定该SharedPreferences的数据只能被本应用程序读、写;
    • Context.MODE_APPEND:新内容追加到原内容后;
    • Context.MODE_WORLD_READABLE:  指定 SharedPreferences数据能被其他应用程序读,但是不支持写;
    • Context.MODE_WORLD_WRITEABLE:  指定 SharedPreferences数据能被其他应用程序读、写。会覆盖原数据。 
    • 可以使用  +  连接这些权限

    2、调用edit()方法获取SharedPreferences.Editor;

    3、通过SharedPreferences.Editor接口提供的put()方法对SharedPreferences进行更新;

    4、调用SharedPreferences.Editorcommit()方法,将更新提交到SharedPreferences中。

    (三)、核心代码:

    @Override

    protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    sp = getSharedPreferences("mysp", MODE_PRIVATE);

    }

    public void btnClick(View v) {

    // 获得一个编辑器

    Editor edit = sp.edit();

    edit.putString("name", "张三");

    edit.putInt("age", 30);

    // 提交数据

    edit.commit();

    }

    public void readData(View v) {

    String name = sp.getString("name", "lisi");

    int age = sp.getInt("age", 0);

    Log.d("qianfeng", "name:" + name + ";age:" + age);

    }

    (四)、保存之后的SharedPreferences数据文件:

            SharedPreferences数据总是以xml格式保存在:/data/data/包名/shared_prefs目录下;

    例如:

    三、External Storage之SDCard操作:

    (一)、读写SD卡的步骤:

    1、先判断手机是否有sd卡;

            调用EnvironmentgetExternalStorageState()方法判断手机是否插上sdcard

    2、获取sdcard的路径;

            调用EnvironmentgetExternalStorageDirectory()方法来获取外部存储器的目录。

    3、此外还可以获取SDCard可用磁盘空间的大小(借助StatFs类来实现);

    4、清单文件中设置读写sdcard的权限;

            <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>   sdcard中创建与删除文件的权限

            <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>   sdcard写入权限

    5、执行读写操作(基本IO流操作)。

    【备注:】

    Environment.getExternalStorageDirectory().getPath()来获取sdcard路径,如果您需要往sdcard中保存特定类型的内容,可以考虑使用Environment.getExternalStoragePublicDirectory(String type)方法,该方法可以返回特定类型的目录,目前支持如下类型:

    1. DIRECTORY_ALARMS //警报的铃声 
    2. DIRECTORY_DCIM //相机拍摄的图片和视频保存的位置 
    3. DIRECTORY_DOWNLOADS //下载文件保存的位置 
    4. DIRECTORY_MOVIES //电影保存的位置, 比如 通过google play下载的电影 
    5. DIRECTORY_MUSIC //音乐保存的位置 
    6. DIRECTORY_NOTIFICATIONS //通知音保存的位置 
    7. DIRECTORY_PICTURES //下载的图片保存的位置 
    8. DIRECTORY_PODCASTS //用于保存podcast(博客)的音频文件 
    9. DIRECTORY_RINGTONES //保存铃声的位置

    【备注:】

            应用程序在运行的过程中如果需要向手机上保存数据,一般是把数据保存在SDcard中的。大部分应用是直接在SDCard的根目录下创建一个文件夹,然后把数据保存在该文件夹中。这样当该应用被卸载后,这些数据还保留在SDCard中,留下了垃圾数据。如果你想让你的应用被卸载后,与该应用相关的数据也清除掉,该怎么办呢?

    • 通过Context.getExternalFilesDir()方法可以获取到 SDCard/Android/data/应用的包名/files/ 目录,一般放一些长时间保存的数据  设置->应用->应用详情里面的清除数据 Clear Data“
    • 通过Context.getExternalCacheDir()方法可以获取到 SDCard/Android/data/应用包名/cache/目录,一般存放临时缓存数据            设置->应用->应用详情里面的清除缓存“ Clear Cache
    • 如果使用上面的方法,当你的应用在被用户卸载后,SDCard/Android/data/你的应用的包名/ 这个目录下的所有文件都会被删除,不会留下垃圾信息。

            而且上面二个目录分别对应 设置->应用->应用详情里面的”清除数据“与”清除缓存“选项。当然如果要保存下载的内容,就不要放在以上目录下。

    (二)、SDCard私有文件目录:

    1、私有目录的files目录下有分为以下7种(无DIRECTORY_DCIM和DIRECTORY_DOWNLOADS):

    • DIRECTORY_ALARMS 
    • DIRECTORY_MOVIES
    • DIRECTORY_MUSIC 
    • DIRECTORY_NOTIFICATIONS 
    • DIRECTORY_PICTURES  
    • DIRECTORY_PODCASTS 
    • DIRECTORY_RINGTONES 

    2、私有目录的cache目录:

    (三)、封装SDCard的工具类:SDCardHelper类

    package lenve.sdcardutils;

    import android.content.Context;

    import android.graphics.Bitmap;

    import android.graphics.BitmapFactory;

    import android.os.Environment;

    import android.os.StatFs;

    import java.io.BufferedInputStream;

    import java.io.BufferedOutputStream;

    import java.io.ByteArrayOutputStream;

    import java.io.File;

    import java.io.FileInputStream;

    import java.io.FileNotFoundException;

    import java.io.FileOutputStream;

    import java.io.IOException;

    /**

     * Created by wangsong on 2016/3/5.

     */

    public class SDCardUtils {

        /**

         * 判断SD卡是否被挂载

         *

         * @return

         */

        public static boolean isSDCardMounted() {

            return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

        }

        /**

         * 获取SD卡的根目录

         *

         * @return

         */

        public static String getSDCardBaseDir() {

            if (isSDCardMounted()) {

                return Environment.getExternalStorageDirectory().getAbsolutePath();

            }

            return null;

        }

        /**

         * 获取SD卡的完整空间大小

         *

         * @return 返回MB

         */

        public static long getSDCardSize() {

            if (isSDCardMounted()) {

                StatFs statFs = new StatFs(getSDCardBaseDir());

                long count = statFs.getBlockCountLong();

                long size = statFs.getBlockSizeLong();

                return count * size / 1024 / 1024;

            }

            return 0;

        }

        /**

         * 获得SD卡剩余空间大小

         *

         * @return

         */

        public static long getSDCardFreeSize() {

            if (isSDCardMounted()) {

                StatFs statFs = new StatFs(getSDCardBaseDir());

                long count = statFs.getFreeBlocksLong();

                long size = statFs.getBlockSizeLong();

                return count * size / 1024 / 1024;

            }

            return 0;

        }

        /**

         * 获取SD卡可用空间大小

         *

         * @return

         */

        public static long getSDCardAvailableSize() {

            if (isSDCardMounted()) {

                StatFs statFs = new StatFs(getSDCardBaseDir());

                long count = statFs.getAvailableBlocksLong();

                long size = statFs.getBlockSizeLong();

                return count * size / 1024 / 1024;

            }

            return 0;

        }

        /**

         * 往SD卡公有目录下保存文件

         *

         * @param data

         * @param type

         * @param fileName

         * @return

         */

        public static boolean saveData2SDCardPublicDir(byte[] data, String type, String fileName) {

            if (isSDCardMounted()) {

                BufferedOutputStream bos = null;

                File file = Environment.getExternalStoragePublicDirectory(type);

                try {

                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));

                    bos.write(data);

                    bos.flush();

                    return true;

                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } finally {

                    if (bos != null) {

                        try {

                            bos.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

            return false;

        }

        /**

         * 往自定义文件中保存数据

         *

         * @param data

         * @param dir

         * @param fileName

         * @return

         */

        public static boolean saveData2SDCardCustomDir(byte[] data, String dir, String fileName) {

            if (isSDCardMounted()) {

                BufferedOutputStream bos = null;

                File file = new File(getSDCardBaseDir() + File.separator + dir);

                if (!file.exists()) {

                    file.mkdirs();

                }

                try {

                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));

                    bos.write(data);

                    bos.flush();

                    return true;

                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } finally {

                    if (bos != null) {

                        try {

                            bos.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

            return false;

        }

        /**

         * 往SD卡的私有Files目录下保存文件

         *

         * @param data

         * @param type

         * @param fileName

         * @param context

         * @return

         */

        public static boolean saveData2SDCardPrivateFilesDir(byte[] data, String type, String fileName, Context context) {

            if (isSDCardMounted()) {

                BufferedOutputStream bos = null;

                File file = context.getExternalFilesDir(type);

                try {

                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));

                    bos.write(data);

                    bos.flush();

                    return true;

                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } finally {

                    if (bos != null) {

                        try {

                            bos.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

            return false;

        }

        /**

         * 往SD卡的私有Cache目录下保存文件

         *

         * @param data

         * @param type

         * @param fileName

         * @param context

         * @return

         */

        public static boolean saveData2SDCardPrivateCacheDir(byte[] data, String type, String fileName, Context context) {

            if (isSDCardMounted()) {

                BufferedOutputStream bos = null;

                File file = context.getExternalCacheDir();

                try {

                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));

                    bos.write(data);

                    bos.flush();

                    return true;

                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } finally {

                    if (bos != null) {

                        try {

                            bos.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

            return false;

        }

        /**

         * 往SD卡的私有目录的Cache文件夹下保存Bitmap图像

         *

         * @param bitmap

         * @param fileName

         * @param context

         * @return

         */

        public static boolean saveBitmap2SDCardPrivateCacheDir(Bitmap bitmap, String fileName, Context context) {

            if (isSDCardMounted()) {

                BufferedOutputStream bos = null;

                File file = context.getExternalCacheDir();

                try {

                    bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));

                    if (fileName != null && (fileName.contains(".png") || (fileName.contains("PNG")))) {

                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);

                    } else {

                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

                    }

                    bos.flush();

                    return true;

                } catch (FileNotFoundException e) {

                    e.printStackTrace();

                } catch (IOException e) {

                    e.printStackTrace();

                } finally {

                    if (bos != null) {

                        try {

                            bos.close();

                        } catch (IOException e) {

                            e.printStackTrace();

                        }

                    }

                }

            }

            return false;

        }

        /**

         * 从SD卡读取指定文件

         *

         * @param filePath

         * @return

         */

        public static byte[] loadFileFromSDCard(String filePath) {

            BufferedInputStream bis = null;

            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            try {

                bis = new BufferedInputStream(new FileInputStream(filePath));

                int len;

                byte[] buf = new byte[1024 * 8];

                while ((len = bis.read(buf)) != -1) {

                    baos.write(buf, 0, len);

                    baos.flush();

                }

                return baos.toByteArray();

            } catch (FileNotFoundException e) {

                e.printStackTrace();

            } catch (IOException e) {

                e.printStackTrace();

            }

            return null;

        }

        /**

         * 从SD卡读取Bitmap并返回

         *

         * @param filePath

         * @return

         */

        public static Bitmap loadBitmapFromSDCard(String filePath) {

            byte[] data = loadFileFromSDCard(filePath);

            if (data != null) {

                return BitmapFactory.decodeByteArray(data, 0, data.length);

            }

            return null;

        }

        /**

         * 获得SD卡公有目录路径

         *

         * @param type

         * @return

         */

        public static String getSDCardPublicDir(String type) {

            if (isSDCardMounted()) {

                return Environment.getExternalStoragePublicDirectory(type).getAbsolutePath();

            }

            return null;

        }

        /**

         * 获取SD卡私有目录Cache文件夹路径

         *

         * @param context

         * @return

         */

        public static String getSDCardPrivateCacheDir(Context context) {

            if (isSDCardMounted()) {

                return context.getExternalCacheDir().getAbsolutePath();

            }

            return null;

        }

        /**

         * 获取SD卡私有目录中Files文件夹路径

         *

         * @param context

         * @param type

         * @return

         */

        public static String getSDCardPrivateFilesDir(Context context, String type) {

            if (isSDCardMounted()) {

                return context.getExternalFilesDir(type).getAbsolutePath();

            }

            return null;

        }

        /**

         * 判断一个文件是否存在

         *

         * @param filePath

         * @return

         */

        public static boolean isFileExists(String filePath) {

            if (isSDCardMounted()) {

                return new File(filePath).exists();

            }

            return false;

        }

        /**

         * 删除一个文件

         *

         * @param filePath

         * @return

         */

        public static boolean removeFileFromSDCard(String filePath) {

            if (isSDCardMounted()) {

                File file = new File(filePath);

                if (file.exists()) {

                    file.delete();

                    return true;

                }

            }

            return false;

        }

    }

  • 相关阅读:
    条款33:避免遮掩继承而来的名称
    LeetCode OJ:Combinations (排列组合)
    LeetCode OJ:Delete Node in a Linked List(链表节点删除)
    LeetCode OJ:Contains Duplicate III(是否包含重复)
    LeetCode OJ:Contains DuplicateII(是否包含重复II)
    luogu 1004 方格取数
    平衡树之伸展树(Splay Tree)题目整理
    P2472 [SCOI2007]蜥蜴(网络最大流)
    P1349 广义斐波那契数列(矩阵加速)
    P4113 [HEOI2012]采花 (莫队TLE)
  • 原文地址:https://www.cnblogs.com/weigongcheng/p/5886394.html
Copyright © 2011-2022 走看看