在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_MUSIC
, DIRECTORY_PICTURES
,DIRECTORY_RINGTONES。根据这些参数系统会自动扫描,并整理到对应的目录中。
Saving files that are app-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, thegetExternalFilesDir()
method provides access
to only th
e internal partition
and your app cannot read or write to the S
D card.
大概意思就是说:如果设备自身已经有了一部分内部存储当做外部存储,那这个方法就不能访问到sd。