Android之数据存储
2010-08-25 23:55:00 来源:WEB开发网protected void onStop(){
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("silentMode", mSilentMode);
// Commit the edits!
editor.commit();
}
}
利用APK本身存储
这种存储方式是把文具存储在文件中,其存位置也在app安装目录里,如果用户删除app,随之的文件也将被删除,主要提供两个方法:
openFileOutput()
openFileInput()
两个的返回类型都是FileInputStream,例子如下:
Java代码
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
缓存文件
缓存文件也是存储在app本身的安装目录里,只是和openFileOutput不在一个目录里,缓存目录里面的数据用户是可以用户手动删除的, openFileOutput就不行,getCacheDir()获取缓存目录,根据自己的需求读写文件。
扩展存储
一般指的是SD卡的存储,使用的示例如下:
Java代码
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {