android 数据存储问题

在android 系统存储系统中,分为内部储存(internal Storage)和外部存储(External),SharedPreferences ,当然还有大家熟悉的sqlite dataBase。那有没有办法?可以让多个应用程序的数据共享呢?那就不得不提到contentProvider。我们通常获取通讯录等信息都是通过contentProvider来获取的。关于详细的contentProvider大家可以参考谷歌的开发文档。

现在言归正传。当我们存储一些键值对的时候,我们可以利用SharePreferences这个类。

  • getSharedPreferences() - Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences() - Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.
大概意思就是说,第一个方法,可以这是具体key对应的value。第二个无需设置具体的key值。

Using the Internal Storage(使用内部存储)

  你可以调用   openFileOutput()  。返回 FileOutPutStream。
String FILENAME = "hello_file";
String string = "hello world!";

FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
使用Context.MODE_PRIVATE,使创建的文件私有化,其他app不能访问。

Saving cache files(使用缓存文件)

说明:这里的缓存针对的是内部存储。你可以对此缓存文件设置大小。当设备内部存储空间不足时,系统会自动清除这些缓存文件,来恢复空间。
具体调用的方法: getCacheDir()

 

Using the External Storage(使用外部存储)

在使用外部存储时,我们要注意是否有可用的外部存储和权限。
<manifest ...>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    ...
</manifest>
首先添加相关权限。(注:在4.4 中,如果这些外部是私有化的,你可以不需要添加这些权限)
 

然后我们验证外部存储是否可用。具体方法如下:
public boolean isExternalStorageWritable() {
    String state = Environment.getExternalStorageState();
    if (Environment.MEDIA_MOUNTED.equals(state)) {
        return true;
    }
    return false;
}
如果我们想让自己的存储的文件能够被其他app 读取,我们可以调用 getExternalStoragePublicDirectory() , 可以传入一些你想要的类型,比如 DIRECTORY_MUSICDIRECTORY_PICTURES,DIRECTORY_RINGTONES。根据这些参数系统会自动扫描,并整理到对应的目录中。
  

Saving files that are app-private(保存文件私有化)

为了文件的保密性,你必须保证自己的文件不让其他app读取。你可以使用 getExternalFilesDir() .然后传入
Context.MODE_PRIVATE
再次注意, getExternalFilesDir(),这个方法,不一定总能够访问sd卡中的信息。让我们来看android 开发官网对此是怎么解释的, Som etimes, a device that has allocated a partitio n of the inter nal memo ry  for use as th e external storage may also offer an SD card slot When  such a device  is running Android 4.3  and lower, the  getExternalFilesDir() method provides access  to only th e internal partition  and your app cannot read or write to the S D card.
大概意思就是说:如果设备自身已经有了一部分内部存储当做外部存储,那这个方法就不能访问到sd。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值