Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 數據持久化:保存數據到 ROM 與跨應用文件訪問的權限控制

編輯:關於 Android 程式設計

本文以一個「記住密碼」的登錄示例,講解如何把數據持久化保存到 ROM(內部存儲),以及如何通過文件權限控制實現跨應用的數據訪問。新建一個 Android 工程(這裡選 API 7),其餘按默認下一步即可。

一、布局文件 activity_main.xml

這裡重點介紹 android:hint 屬性,它的作用是在輸入框中顯示提示信息,相當於 Web 項目中的 placeholder。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_info" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="text|number"
        android:hint="@string/et_type_name"
        android:id="@+id/et_name" />
    <EditText
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:inputType="textPassword"
        android:hint="@string/et_type_password"
        android:id="@+id/et_password" />
    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
        <Button
            android:id="@+id/bt_login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginLeft="30dp"
            android:text="@string/bt_login" />
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="150dp"
            android:text="@string/cb_remember_password"
            android:id="@+id/cb_password" />
    </RelativeLayout>
</LinearLayout>

二、MainActivity 的點擊邏輯

public class MainActivity extends Activity implements OnClickListener {
    EditText et_name;      // 用戶名
    EditText et_password;  // 密碼
    Button bt_login;       // 登錄按鈕
    CheckBox cb_password;  // 記住密碼單選框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_name = (EditText) this.findViewById(R.id.et_name);
        et_password = (EditText) this.findViewById(R.id.et_password);
        bt_login = (Button) this.findViewById(R.id.bt_login);
        cb_password = (CheckBox) this.findViewById(R.id.cb_password);
        bt_login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_login:
                if (cb_password.isChecked()) {
                    // 保存數據到 rom
                    new savePasswordService(this).savePasswordToFile(
                            et_name.getText().toString(), et_password.getText().toString());
                    Toast.makeText(this, "保存數據成功!", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "沒有保存數據!", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }
}

這裡用 switch 語句來判斷點擊事件,能使代碼結構更清晰。

三、保存數據的關鍵:savePasswordService

public class savePasswordService {
    private Context context;
    private String tag = "savePasswordService";

    public savePasswordService(Context context) {
        this.context = context;
    }

    public void savePasswordToFile(String name, String password) {
        String content = name + ":" + password;
        try {
            FileOutputStream fileOutput = context.openFileOutput("LoginTestConfig.txt",
                    Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
            fileOutput.write(content.getBytes());
            fileOutput.flush();
            fileOutput.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

關鍵在於調用了 Context 的 openFileOutput() 方法。它的第二個參數控制文件權限,默認是私有的(其他應用不可讀);這裡設置了 MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE,讓其他應用程序也能讀寫該文件。

四、跨應用讀取與數據回顯

新建一個工程 dataread,界面不變,直接以文件路徑 /data/data/com.amos.datasave/files/LoginTestConfig.txt 訪問剛才保存的文件並寫入數據,實驗證明可以成功寫入。如果要實現數據回顯,則可以讀取該文件並解析:

File file = new File("/data/data/com.amos.datasave/files/LoginTestConfig.txt");
try {
    FileInputStream fis = new FileInputStream(file);
    byte[] bytes = new byte[1024];
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    int len;
    while ((len = fis.read(bytes)) > 0) {
        bos.write(bytes, 0, len);
    }
    String result = new String(bos.toByteArray());
    String name = result.split(":")[0];
    String password = result.split(":")[1];
    et_name.setText(name);
    et_password.setText(password);
} catch (Exception e) {
    e.printStackTrace();
}

讀取時通過 FileInputStream 逐塊讀入,用 ByteArrayOutputStream 拼接成完整字符串,再以冒號分割出用戶名和密碼,回填到輸入框中,就實現了「記住密碼」的效果。由此可見,Android 的數據持久化本質上是通過文件 I/O 完成的,而 openFileOutput 的權限參數則決定了數據能否被其他應用訪問——在實際開發中,出於安全考慮,不建議輕易使用 MODE_WORLD_READABLE/WRITEABLE 這類開放權限。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved