編輯:關於 Android 程式設計
幾乎每個 App 都需要提供設定畫面:要不要允許陌生人加好友、要不要開啟通知、上次輸入的帳號是什麼。這些「軟體參數」該存哪裡?
Windows 桌面程式習慣寫 ini 檔,J2SE 應用常用 properties 或 XML。那 Android 呢?平台直接提供了 SharedPreferences——一個輕量級的鍵值儲存類別,專門為這類小型設定資料而生。
用 SharedPreferences 存資料,底層會產生一個 XML 檔,位置在:
/data/data/<package name>/shared_prefs/
寫入程式碼:
SharedPreferences sp = getSharedPreferences("itcast", Context.MODE_PRIVATE);
Editor editor = sp.edit(); // 取得編輯器
editor.putString("name", "趙雅智部落格");
editor.putInt("age", 4);
editor.commit(); // 記得提交,否則不會落地
產生的 itcast.xml 內容長這樣:
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">趙雅智部落格</string>
<int name="age" value="4" />
</map>
.xml。Context.MODE_WORLD_READABLE 與 Context.MODE_WORLD_WRITEABLE。另外,Activity 還提供 getPreferences(mode),它會預設拿當前類別的類名(不含套件名)當作檔名,省下手動命名的麻煩。
SharedPreferences sp = getSharedPreferences("itcast", Context.MODE_PRIVATE);
// 第二個參數是預設值:key 不存在時就回傳它
String name = sp.getString("name", "");
int age = sp.getInt("age", 1);
那個「預設值」參數常被忽略,但少了它,一旦 key 不存在就會拿到 null 或直接拋出例外,務必養成習慣。
想讀別的 App 存的 Preference,前提是對方建立時使用了 MODE_WORLD_READABLE 或 MODE_WORLD_WRITEABLE。假設套件名為 cn.itcast.action 的應用這樣建立:
getSharedPreferences("itcast", Context.MODE_WORLD_READABLE);
其他應用要先建立對方的 Context,再透過它取得 Preference:
Context otherAppsContext = createPackageContext("cn.itcast.action",
Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences sp = otherAppsContext.getSharedPreferences(
"itcast", Context.MODE_WORLD_READABLE);
String name = sp.getString("name", "");
int age = sp.getInt("age", 0);
如果不走 Context,也可以直接以 XML 檔路徑去讀對方的檔案:
File xmlFile = new File(
"/data/data/<package name>/shared_prefs/itcast.xml");
不過要留意:這類跨應用公開設定檔的做法在後續 Android 版本已被大幅限制,現行方案應改用 ContentProvider 或 FileProvider 分享資料。
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="com.example.lession03_login"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.lession03_login.LoginActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
與 SD 卡版本相同的登入畫面:帳號、密碼、ROM / SP / SD 三個單選鈕、登入鈕與「記住密碼」核取方塊。
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_name" />
<EditText
android:id="@+id/edit_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:id="@+id/view_pass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_pass" />
<EditText
android:id="@+id/edit_pass"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ems="10"
android:inputType="textPassword" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<RadioGroup
android:id="@+id/radioGroup1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:ignore="UselessParent" >
<RadioButton
android:id="@+id/radio_rom"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="@string/login_rom" />
<RadioButton
android:id="@+id/radio_sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_sp" />
<RadioButton
android:id="@+id/radio_sd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_sd" />
</RadioGroup>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/button_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login_login" />
<CheckBox
android:id="@+id/check_remember"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="@string/login_remember" />
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">lession03_login</string>
<string name="login_name">使用者名稱</string>
<string name="login_pass">密碼</string>
<string name="login_login">登入</string>
<string name="login_remember">記住密碼</string>
<string name="login_rom">ROM 儲存</string>
<string name="login_sp">SP 儲存</string>
<string name="login_sd">SD 儲存</string>
</resources>
SP 的寫入流程固定三步:getSharedPreferences() 取物件、edit() 取編輯器、commit() 提交。
package com.example.lession03_login.service;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class LoginService {
private Context context;
public LoginService(Context context) {
super();
this.context = context;
}
/**
* 以 SharedPreferences 儲存帳號與密碼
*/
public boolean saveBysp(String name, String pass, String fileName) {
SharedPreferences sp = context.getSharedPreferences(
fileName, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("name", name);
editor.putString("pass", pass);
return editor.commit();
}
}
package com.example.lession03_login;
import com.example.lession03_login.service.LoginService;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Checkable;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class LoginActivity extends Activity {
private EditText edit_name, edit_pass;
private Button btn_login;
private Checkable box_remember;
private LoginService loginService;
private RadioButton radio_rom, radio_sp, radio_sd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginService = new LoginService(this);
edit_name = (EditText) findViewById(R.id.edit_name);
edit_pass = (EditText) findViewById(R.id.edit_pass);
btn_login = (Button) findViewById(R.id.button_login);
box_remember = (Checkable) findViewById(R.id.check_remember);
radio_rom = (RadioButton) findViewById(R.id.radio_rom);
radio_sp = (RadioButton) findViewById(R.id.radio_sp);
radio_sd = (RadioButton) findViewById(R.id.radio_sd);
btn_login.setOnClickListener(new MyOnclickListener());
// 回顯上次儲存的資料
SharedPreferences preferences =
this.getSharedPreferences("csdn", Context.MODE_PRIVATE);
edit_name.setText(preferences.getString("name", ""));
edit_pass.setText(preferences.getString("pass", ""));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
class MyOnclickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.button_login:
String name = edit_name.getText().toString();
String pass = edit_pass.getText().toString();
if (TextUtils.isEmpty(name)) {
Toast.makeText(LoginActivity.this, "使用者名稱不可為空",
Toast.LENGTH_LONG).show();
return;
} else if (TextUtils.isEmpty(pass)) {
Toast.makeText(LoginActivity.this, "密碼不可為空",
Toast.LENGTH_LONG).show();
return;
}
if (box_remember.isChecked()) {
if (radio_sp.isChecked()) {
boolean flag = loginService.saveBysp(name, pass, "csdn");
Toast.makeText(LoginActivity.this,
flag ? "儲存成功" : "儲存失敗",
Toast.LENGTH_LONG).show();
}
// radio_rom / radio_sd 的實作留給讀者自行補上
} else {
Toast.makeText(LoginActivity.this, "不儲存密碼",
Toast.LENGTH_LONG).show();
}
break;
default:
break;
}
}
}
}
第一次進入時欄位是空的:
輸入帳密並勾選「記住密碼」後按下登入:
手動清空欄位後重新進入:
帳密自動回來了:
再按一次登入,資料被重新寫入:
EncryptedSharedPreferences。
Android 用 PullToRefresh 實作下拉刷新與上拉加載
先放一張執行結果圖,如果看著順眼,就繼續往下讀。 延伸閱讀:分享 Android 中 pullToRefresh 的使用心得 專案已同步至 GitHub:https:/
Android 中 Thread、Handler、Looper 與 MessageQueue 原理剖析
Thread、Handler、Looper 這三個類別在 Android 開發中幾乎無所不在,但剛入門時往往只會用、知其然而不知其所以然。這篇就從源碼角度把這套機制拆開來
Android UI 控件之 ProgressBar:從系統樣式到自定義圓形進度條
(一)概述 ProgressBar 是 Android 裡反饋「正在進行中」的基礎控件。它既可以表達確定的百分比,也可以表達不確定的忙碌狀態。 (二)常用屬性與基礎實
微信收錢新功能:掃一掃收款與二維碼分享教學
微信6.2新增收錢功能。升級後在首頁點右上角加號,選擇收錢,可設定金額並產生二維碼。 面對面時直接讓對方掃碼;遠端收款可截圖傳給好友或群組。對方掃碼後確認支付,款項會進入