編輯:關於 Android 程式設計
Android 官方把 Data Storage 分成 Storage Options 五類,這是理解後續所有存儲 API 的地基:
幾個容易踩坑的認知問題,先說清楚:
getFilesDir() 返回你 app 在內部存儲上的根目錄。SharedPreferences 是 Android 提供的通用數據持久化框架,用於存儲和讀取 key-value 形式的原始基本類型對,目前支持 string、int、long、float、boolean 等;自定義對象存不進去。它最典型的用途是保存系統配置信息:上次登錄的用戶名、音效和振動開關、小遊戲的最高積分等等,讓 app 下次啟動時還能延續上次的設置。鍵值對的形式天然適合寫入和讀取。
edit() 拿到 SharedPreferences.Editor。putXxx() 系列方法寫入數據。commit() 提交,這一步之前數據不會落盤。1. Context.getSharedPreferences(String name, int mode)
第一個參數指定文件名,文件不存在時會新建,落盤路徑是 /data/data/包名/shared_prefs/;第二個參數指定讀寫模式,可選值如下:
Context.MODE_PRIVATE:默認模式,數據僅當前應用可讀寫;同名文件會被新內容覆蓋。Context.MODE_APPEND:文件已存在時不新建,改為往原文件追加內容。Context.MODE_MULTI_PROCESS:多進程同時讀寫同一個文件時使用。Context.MODE_WORLD_READABLE:允許其他應用讀但不允許寫,Android 4.2 起已廢棄。Context.MODE_WORLD_WRITEABLE:允許其他應用讀寫,會覆蓋原數據,Android 4.2 起已廢棄。+ 位運算組合。2. Activity.getPreferences(int mode)
與上面那個方法相似,但只有 mode 一個參數,並會自動拿當前 Activity 的類名作為文件名。
3. PreferenceManager.getDefaultSharedPreferences(Context context)
靜態方法,接收一個 Context,會以應用包名作為前綴自動命名。例如包名為 org.mobiletrain.preferenceactivity 的應用,會在 /data/data/org.mobiletrain.preferenceactivity/shared_prefs/ 下生成 org.mobiletrain.preferenceactivity_preferences.xml。
順帶說一下沙盒(sandbox)。每個 app 都有一個放在沙盒中的私有文件目錄,路徑是 /data/data/包名,別的 app 進不去。沙盒這套虛擬化技術在計算機安全領域很常見,原理是通過重定向把程序生成和修改的文件全部導向自身文件夾,讓可疑程序先在隔離環境裡跑,一旦出現惡意行為就直接掐斷,不危害系統。
button_main_savedata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt("age", 38);
editor.putString("username", "wangxiangjun");
editor.putString("pwd", "123456");
editor.putString("username", "xiangjun"); // 同名 key 後寫覆蓋前寫
editor.commit();
}
});
button_main_readdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prefs = getSharedPreferences("myaccount", Context.MODE_PRIVATE);
String name = prefs.getString("username", "wxj"); // 第二個參數是默認值
String pwd = prefs.getString("pwd", "000");
int age = prefs.getInt("age", 20);
System.out.println("====>" + name + ":" + pwd + ":" + age);
}
});
SharedPreferences 數據一律以 xml 格式保存在 /data/data/包名/shared_prefs 目錄下:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="pwd">123456</string>
<string name="username">xiangjun</string>
<int name="age" value="20" />
</map>
手機裡那種系統風格的設置頁面:
如果按傳統思路做,得寫一個繁瑣的布局再加一堆監聽。其實用 PreferenceActivity 會省事很多,步驟是:
setting.xml 放到 res/xml 目錄下;arrays.xml 放到 res/values 目錄下;目錄結構:
代碼非常短,注意不再需要 setContentView():
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
addPreferencesFromResource(R.xml.setting);
// 注意:該方法在 API level 11 中被標記為 deprecated,
// 基於 fragment 的現代 PreferenceActivity 不再使用它。
}
public class MainActivity extends Activity {
private ListView listView_main_blockList;
private EditText editText_main_number;
private TextView textView_main_emptyinfo;
private SharedPreferences prefs = null;
private Editor editor = null;
private ArrayAdapter<String> adapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText_main_number = (EditText) findViewById(R.id.editText_main_number);
listView_main_blockList = (ListView) findViewById(R.id.listView_main_blocklist);
textView_main_emptyinfo = (TextView) findViewById(R.id.text_main_emptyinfo);
prefs = getSharedPreferences("blocklist", Context.MODE_PRIVATE);
editor = prefs.edit();
List<String> list = getBlocklist();
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
// setEmptyView():適配器為空時展示的替代視圖
listView_main_blockList.setEmptyView(textView_main_emptyinfo);
listView_main_blockList.setAdapter(adapter);
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_add:
String mpnumber = editText_main_number.getText().toString();
editor.putString(mpnumber, mpnumber);
editor.commit();
fillListView();
break;
case R.id.button_main_clear:
editor.clear();
editor.commit();
fillListView();
break;
default:
break;
}
}
/** 取出 SharedPreferences 中的全部數據,組合成適配器的數據源 */
private List<String> getBlocklist() {
List<String> list = new ArrayList<String>();
try {
Map<String, ?> map = prefs.getAll();
for (Map.Entry<String, ?> entry : map.entrySet()) {
list.add(entry.getKey());
}
return list;
} catch (Exception e) {
return null;
}
}
/** 刷新 ListView 顯示 */
private void fillListView() {
adapter.clear();
adapter.addAll(getBlocklist());
}
}
Context 類提供了一組文件和目錄處理方法,都是圍繞 /data/data/包名 這個私有空間:
getCacheDir():內部緩存目錄 /data/data/包名/cache,應及時清理、節約使用。getFilesDir():內部文件目錄 /data/data/包名/files,注意它和 SharedPreferences 的 /data/data/包名/shared_prefs 不是同一個地方。String[] fileList():列出 files 目錄下的文件。openFileInput(String name):打開 files 目錄下的文件讀取。openFileOutput(String name, int mode):打開內部存儲上的文件寫入,不存在則創建。Android 提供了 openFileInput() 和 openFileOutput() 這對專屬方法做 IO,但機內存儲實在有限。要存大文件,就得讀寫 SD 卡。
Environment.getExternalStorageState()。Environment.getExternalStorageDirectory()。StatFs 類查可用磁盤空間。MOUNT_UNMOUNT_FILESYSTEMS(掛載/卸載,即在 SD 卡中創建與刪除文件)、READ_EXTERNAL_STORAGE(讀)、WRITE_EXTERNAL_STORAGE(寫)。如果想把文件存到特定類型的公共目錄,可以用 Environment.getExternalStoragePublicDirectory(String type),目前支持的類型包括:
DIRECTORY_ALARMS:鬧鈴鈴聲DIRECTORY_DCIM:相機拍攝的圖片和視頻DIRECTORY_DOWNLOADS:下載文件DIRECTORY_MOVIES:電影DIRECTORY_MUSIC:音樂DIRECTORY_NOTIFICATIONS:通知音DIRECTORY_PICTURES:圖片DIRECTORY_PODCASTS:播客音頻DIRECTORY_RINGTONES:鈴聲還有一個常被忽略的問題:多數應用習慣直接在 SD 卡根目錄下建一個文件夾存數據,結果卸載之後垃圾數據還留在卡上。想讓卸載時自動清理,就用下面這兩個目錄:
Context.getExternalFilesDir() → SDCard/Android/data/包名/files/,放需要長期保存的數據,對應設置裡的「清除數據 Clear Data」。Context.getExternalCacheDir() → SDCard/Android/data/包名/cache/,放臨時緩存,對應「清除緩存 Clear Cache」。用這兩個方法的好處是:卸載時 SDCard/Android/data/包名/ 整個目錄會被刪掉,不留垃圾。當然,如果保存的是下載內容(用戶期望卸載後仍在),就不要放這裡。私有 files 目錄下同樣分了 7 種子類型:DIRECTORY_ALARMS、DIRECTORY_MOVIES、DIRECTORY_MUSIC、DIRECTORY_NOTIFICATIONS、DIRECTORY_PICTURES、DIRECTORY_PODCASTS、DIRECTORY_RINGTONES(注意少了 DCIM 和 DOWNLOADS)。
把掛載判斷、空間查詢、各類目錄讀寫都收攏到一個工具類裡,業務代碼會乾淨很多。核心方法如下:
public class SDCardHelper {
/** 判斷 SD 卡是否已掛載 */
public static boolean isSDCardMounted() {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
}
/** SD 卡根目錄 */
public static String getSDCardBaseDir() {
if (isSDCardMounted()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
/** 總容量,單位 MB */
public static long getSDCardSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return (long) fs.getBlockCount() * fs.getBlockSize() / 1024 / 1024;
}
return 0;
}
/** 剩余空間 */
public static long getSDCardFreeSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return (long) fs.getFreeBlocks() * fs.getBlockSize() / 1024 / 1024;
}
return 0;
}
/** 可用空間 */
public static long getSDCardAvailableSize() {
if (isSDCardMounted()) {
StatFs fs = new StatFs(getSDCardBaseDir());
return (long) fs.getAvailableBlocks() * fs.getBlockSize() / 1024 / 1024;
}
return 0;
}
/** 寫入 SD 卡公有目錄 */
public static boolean saveFileToSDCardPublicDir(byte[] data, String type, String fileName) {
if (!isSDCardMounted()) return false;
BufferedOutputStream bos = null;
try {
File dir = Environment.getExternalStoragePublicDirectory(type);
bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
}
return false;
}
/** 寫入 SD 卡自定義目錄(不存在則遞歸創建) */
public static boolean saveFileToSDCardCustomDir(byte[] data, String dir, String fileName) {
if (!isSDCardMounted()) return false;
BufferedOutputStream bos = null;
try {
File file = new File(getSDCardBaseDir() + File.separator + dir);
if (!file.exists()) file.mkdirs();
bos = new BufferedOutputStream(new FileOutputStream(new File(file, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
}
return false;
}
/** 寫入私有 files 目錄:SDCard/Android/data/包名/files/ */
public static boolean saveFileToSDCardPrivateFilesDir(byte[] data, String type,
String fileName, Context context) {
if (!isSDCardMounted()) return false;
BufferedOutputStream bos = null;
try {
File dir = context.getExternalFilesDir(type);
bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
}
return false;
}
/** 寫入私有 cache 目錄 */
public static boolean saveFileToSDCardPrivateCacheDir(byte[] data, String fileName,
Context context) {
if (!isSDCardMounted()) return false;
BufferedOutputStream bos = null;
try {
File dir = context.getExternalCacheDir();
bos = new BufferedOutputStream(new FileOutputStream(new File(dir, fileName)));
bos.write(data);
bos.flush();
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (bos != null) bos.close(); } catch (IOException e) { e.printStackTrace(); }
}
return false;
}
/** 從 SD 卡任意路徑讀文件,返回字節數組 */
public static byte[] loadFileFromSDCard(String fileDir) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
bis = new BufferedInputStream(new FileInputStream(new File(fileDir)));
byte[] buffer = new byte[8 * 1024];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
baos.close();
if (bis != null) bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String getSDCardPublicDir(String type) {
return Environment.getExternalStoragePublicDirectory(type).toString();
}
public static String getSDCardPrivateCacheDir(Context context) {
return context.getExternalCacheDir().getAbsolutePath();
}
public static String getSDCardPrivateFilesDir(Context context, String type) {
return context.getExternalFilesDir(type).getAbsolutePath();
}
}
點第一個按鈕從網絡拉圖片存盤,點第二個按鈕把剛存的圖讀出來貼到 ImageView 上。網絡請求放在 AsyncTask 裡,避免阻塞主線程:
public class MainActivity extends Activity {
private ImageView imageView_main_img;
private String urlString = "https://t2.baidu.com/it/u=2,1891512358&fm=19&gp=0.jpg";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView_main_img = (ImageView) findViewById(R.id.imageView_main_img);
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.button_main_save:
new MyTask(this).execute(urlString);
break;
case R.id.button_main_show:
String filepath = SDCardHelper.getSDCardPath() + File.separator
+ "mydir" + File.separator + "firstimg.jpg";
byte[] data = SDCardHelper.loadFileFromSDCard(filepath);
if (data != null) {
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView_main_img.setImageBitmap(bm);
} else {
Toast.makeText(this, "沒有該圖片!", Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
class MyTask extends AsyncTask<String, Void, byte[]> {
private Context context;
private ProgressDialog pDialog;
public MyTask(Context context) {
this.context = context;
pDialog = new ProgressDialog(context);
pDialog.setIcon(R.drawable.ic_launcher);
pDialog.setMessage("圖片加載中...");
}
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog.show();
}
@Override
protected byte[] doInBackground(String... params) {
BufferedInputStream bis = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
URL url = new URL(params[0]);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setDoInput(true);
httpConn.connect();
if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
byte[] buffer = new byte[1024 * 8];
int c = 0;
while ((c = bis.read(buffer)) != -1) {
baos.write(buffer, 0, c);
baos.flush();
}
return baos.toByteArray();
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(byte[] result) {
super.onPostExecute(result);
if (result == null) {
Toast.makeText(context, "圖片加載失敗!", Toast.LENGTH_LONG).show();
} else {
if (SDCardHelper.saveFileToSDCard(result, "mydir", "firstimg.jpg")) {
Toast.makeText(context, "圖片保存OK!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context, "圖片保存失敗!", Toast.LENGTH_LONG).show();
}
}
pDialog.dismiss();
}
}
}
原理不複雜:用 File.listFiles() 拿到 File[] 數組,把信息填進 ListView。核心 API 就這幾個:listFiles()、isFile()、isDirectory()、getAbsolutePath()、getParentFile()。
public class MainActivity extends Activity {
private TextView textView_main_currentpath;
private ListView listView_main_fileList;
private File currentFile = null;
private File[] arrCurrentFiles = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView_main_currentpath = (TextView) findViewById(R.id.text_main_currentpath);
listView_main_fileList = (ListView) findViewById(R.id.listView_main_filelist);
if (SDCardHelper.isSDCardMounted()) {
currentFile = new File(SDCardHelper.getSDCardPath());
fillListView(currentFile);
} else {
Toast.makeText(MainActivity.this, "SDCARD不存在!", Toast.LENGTH_LONG).show();
}
listView_main_fileList.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (arrCurrentFiles[position].isDirectory()) {
File[] arrSubFiles = arrCurrentFiles[position].listFiles();
if (arrSubFiles.length == 0) {
Toast.makeText(MainActivity.this, "您點擊的是空目錄!", 2000).show();
} else {
fillListView(arrCurrentFiles[position]); // 進入子目錄
}
} else {
Toast.makeText(MainActivity.this, "您點擊的不是目錄!", Toast.LENGTH_LONG).show();
}
}
});
}
public void clickButton(View view) {
switch (view.getId()) {
case R.id.imageView_main_back:
// 已經在根目錄就不再往上跳
if (!currentFile.getAbsolutePath().equals(SDCardHelper.getSDCardPath())) {
fillListView(currentFile.getParentFile());
}
break;
default:
break;
}
}
public void fillListView(File file) {
currentFile = file;
arrCurrentFiles = currentFile.listFiles();
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
for (int i = 0; i < arrCurrentFiles.length; i++) {
Map<String, Object> map = new HashMap<String, Object>();
if (arrCurrentFiles[i].isDirectory()) {
map.put("imgId", R.drawable.folder);
} else {
map.put("imgId", R.drawable.file);
}
map.put("filename", arrCurrentFiles[i].getName());
list.add(map);
}
SimpleAdapter adapter = new SimpleAdapter(MainActivity.this, list,
R.layout.item_listview_main,
new String[] { "imgId", "filename" },
new int[] { R.id.imageView_item_listview_type, R.id.text_item_listview_filename });
listView_main_fileList.setAdapter(adapter);
textView_main_currentpath.setText(currentFile.getAbsolutePath());
}
}
最後再提一個同類案例:SDCard 圖片浏覽器。做法和文件浏覽器幾乎一樣,只是把 listFiles() 的結果過濾成圖片文件,再把縮略圖交給適配器渲染即可。
整體來看,Android 的存儲方案選型其實很清晰:輕量的配置項用 SharedPreferences,私有小文件用內部存儲,結構化數據用 SQLite,大文件和需要跨應用共享的公共資源放外部存儲。關鍵是把「私有目錄會隨卸載清理」這件事想清楚,再決定數據到底該落在哪。
Android 左右滑動切換頁面:ViewPager 與底部指示條實作
許多常見 App 都支援左右滑動切換頁面,例如影片與音樂分頁、新聞與動態切換等。這種互動在 Android 中可以透過 ViewPager 搭配 PagerAdapter
登入欄位的郵箱自動補全:自訂 AutoCompleteTextView 實作拆解
輸入帳號時自動補上 @qq.com、@163.com 這類後綴,是很常見的貼心設計。本文示範如何從零打造這個功能。 實作要點: 繼承並複寫 AutoCompleteT
Android 自定義繪製:打造線條由細漸粗的手繪路徑
一、效果預覽 用過電腦版筆記軟體書寫演示功能的朋友,應該對這種筆觸由細變粗的效果不陌生。本文要探討的,正是如何在手機端一步步還原它。完整的目標是模擬出順暢自然的書寫筆跡
Android 上傳文件到服務端並實時顯示進度
最近在做文件上傳的服務,看了不少教程,多數只講客戶端、不給服務端,可沒有服務端根本沒法調試。所以這裡兩邊都給。 客戶端核心很簡單:HttpURLConnection 加上