編輯:關於 Android 程式設計
幾乎所有騷擾攔截類應用都有「定時攔截」這個功能,實作難度其實不高。核心是三件事:用 ToggleButton 控制開關、用 Dialog 挑選起訖時間、用 SharedPreferences 把設定存下來。



未啟用時,開始時間與結束時間兩列呈灰色且點擊無回應;啟用後文字變黑、可點擊,點下去彈出日期與時間選擇對話框。
1. 在布局中定義三個 ToggleButton 與兩列時間顯示。
2. 從布局取得控制項,為 ToggleButton 掛 OnCheckedChangeListener、為兩列時間掛 OnClickListener。
3. 用 SharedPreferences 保存開關狀態與起訖時間。
4. 用「文字顏色 + setClickable」這組組合表達啟用狀態。
5. 用 AlertDialog 內嵌 DatePicker 與 TimePicker 完成選擇。
private ToggleButton tb_switch, tb_whiteList, tb_time; private RelativeLayout start_layout; private RelativeLayout end_layout; private TextView tv_start_time, tv_start_tip; private TextView tv_end_time, tv_end_tip; private SharedPreferences sp; SharedPreferences.Editor editor;
sp = this.getSharedPreferences("setting", Activity.MODE_PRIVATE);
editor = sp.edit();
start_layout = (RelativeLayout) findViewById(R.id.start_layout);
start_layout.setOnClickListener(new ClickEvent());
start_layout.setClickable(false); // 預設不可點
end_layout = (RelativeLayout) findViewById(R.id.end_layout);
end_layout.setOnClickListener(new ClickEvent());
end_layout.setClickable(false);
tv_start_time = (TextView) findViewById(R.id.tv_start_time);
tv_end_time = (TextView) findViewById(R.id.tv_end_time);
tv_start_tip = (TextView) findViewById(R.id.tv_start_tip);
tv_end_tip = (TextView) findViewById(R.id.tv_end_tip);
tb_switch = (ToggleButton) findViewById(R.id.tb_switch);
tb_whiteList = (ToggleButton) findViewById(R.id.tb_whitelist);
tb_time = (ToggleButton) findViewById(R.id.tb_time);
tb_switch.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
tb_whiteList.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
tb_time.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
注意這裡是對 RelativeLayout 掛 OnClickListener 而非對裡面的 TextView。這樣整列都是可點區域,使用者的觸控不必精準落在文字上。
這個元件用來保存少量簡單設定,用法固定三步:
1. 取得物件
SharedPreferences sp = this.getSharedPreferences("setting", Activity.MODE_PRIVATE);
第二個參數是存取模式,MODE_PRIVATE 表示僅本應用可讀寫,其餘模式(MODE_WORLD_READABLE 等)在新版系統中已被移除。
2. 寫入並提交
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean("isStartListen", true);
editor.commit(); // 提交後資料才會寫進 setting.xml
commit() 是同步寫入並回傳 boolean 結果;apply() 是非同步、沒有回傳值但效能更好。在主執行緒上建議用 apply()。
3. 讀取
boolean data = sp.getBoolean("isStartListen", false);
第二個參數是預設值——若檔案中不存在這個 key,就回傳它。這個設計讓程式不必先判斷 key 是否存在。
class ToggleButtonCheckedEvent implements OnCheckedChangeListener {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (buttonView.getId() == R.id.tb_switch) {
tb_switch.setChecked(isChecked);
if (isChecked) {
editor.putBoolean("isStartListen", true);
editor.commit();
tb_switch.setBackgroundResource(R.drawable.start_service_on);
Toast.makeText(SettingActivity.this, "開啟攔截服務", 1000).show();
} else {
editor.putBoolean("isStartListen", false);
editor.commit();
tb_switch.setBackgroundResource(R.drawable.start_service_off);
Toast.makeText(SettingActivity.this, "關閉攔截服務", 1000).show();
}
}
else if (buttonView.getId() == R.id.tb_whitelist) {
tb_whiteList.setChecked(isChecked);
if (isChecked) {
editor.putBoolean("isWhiteList", true);
tb_whiteList.setBackgroundResource(R.drawable.start_service_on);
Toast.makeText(SettingActivity.this, "白名單模式", 1000).show();
} else {
editor.putBoolean("isWhiteList", false);
tb_whiteList.setBackgroundResource(R.drawable.start_service_off);
Toast.makeText(SettingActivity.this, "黑名單模式", 1000).show();
}
editor.commit();
}
else if (buttonView.getId() == R.id.tb_time) {
tb_time.setChecked(isChecked);
if (isChecked) {
tb_time.setBackgroundResource(R.drawable.start_service_on);
// 啟用:兩列變黑且可點
start_layout.setClickable(true);
end_layout.setClickable(true);
tv_start_tip.setTextColor(Color.BLACK);
tv_start_time.setTextColor(Color.BLACK);
tv_end_tip.setTextColor(Color.BLACK);
tv_end_time.setTextColor(Color.BLACK);
editor.putBoolean("isTime", true);
Toast.makeText(SettingActivity.this, "啟用定時攔截,請設定開始時間和結束時間", 1000).show();
String[] time = getCurrentTime();
tv_start_time.setText(time[0]);
tv_end_time.setText(time[1]);
editor.putString("startTime", time[0]);
editor.putString("endTime", time[1]);
} else {
tb_time.setBackgroundResource(R.drawable.start_service_off);
// 停用:兩列變灰且不可點
tv_start_tip.setTextColor(Color.GRAY);
tv_start_time.setTextColor(Color.GRAY);
tv_end_tip.setTextColor(Color.GRAY);
tv_end_time.setTextColor(Color.GRAY);
start_layout.setClickable(false);
end_layout.setClickable(false);
editor.putBoolean("isTime", false);
Toast.makeText(SettingActivity.this, "關閉定時攔截", 1000).show();
String[] time = getCurrentTime();
tv_start_time.setText(time[0]);
tv_end_time.setText(time[1]);
}
editor.commit();
}
}
}
這個監聽器裡有個值得學的細節:用「顏色 + setClickable」成對表達狀態。只改顏色使用者會困惑(為什麼變灰了還能點?),只設 clickable 又沒有視覺回饋,兩者搭配才完整。
另一點是 tb_switch 與 tb_whiteList 只保存設定,還沒有真正啟動服務。因為攔截功能尚未完成,這裡先把狀態存起來,後續實作 Service 時再補上對應動作。這是分階段開發的正確做法——先讓設定層完整,再串接行為層。
還有個潛在問題值得注意:在 onCheckedChanged 裡呼叫 setChecked() 會再次觸發同一個監聽器,形成遞迴。這段程式之所以沒事,是因為 setChecked 設定的值與當前值相同時不會觸發變化回呼。若你改寫時在其中改了狀態,務必留意。
class ClickEvent implements OnClickListener {
@Override
public void onClick(View v) {
Context mContext = SettingActivity.this;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
View view = View.inflate(mContext, R.layout.data_time_dialog, null);
final DatePicker datePicker = (DatePicker) view.findViewById(R.id.data_picker);
final TimePicker timePicker = (TimePicker) view.findViewById(R.id.time_picker);
builder.setView(view);
// 取得目前日期時間
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(System.currentTimeMillis());
// 將日期選擇器預設為今天
datePicker.init(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH), null);
// 將時間選擇器預設為現在,並使用 24 小時制
timePicker.setIs24HourView(true);
timePicker.setCurrentHour(cal.get(Calendar.HOUR_OF_DAY));
timePicker.setCurrentMinute(cal.get(Calendar.MINUTE));
if (v.getId() == start_layout.getId()) {
builder.setTitle("選擇起始監聽時間");
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
// 格式化日期:月-日
sb.append(String.format("%02d-%02d",
datePicker.getMonth() + 1, datePicker.getDayOfMonth()));
sb.append(" ");
// 格式化時間:時:分
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(), timePicker.getCurrentMinute()));
tv_start_time.setText(sb);
editor.putString("startTime", sb.toString());
editor.commit();
showTimeErrorTip();
dialog.cancel();
}
});
}
else if (v.getId() == end_layout.getId()) {
builder.setTitle("選擇結束監聽時間");
builder.setPositiveButton("確定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
StringBuffer sb = new StringBuffer();
sb.append(String.format("%02d-%02d",
datePicker.getMonth() + 1, datePicker.getDayOfMonth()));
sb.append(" ");
sb.append(String.format("%02d:%02d",
timePicker.getCurrentHour(), timePicker.getCurrentMinute()));
tv_end_time.setText(sb);
editor.putString("endTime", sb.toString());
editor.commit();
showTimeErrorTip();
dialog.cancel();
}
});
}
Dialog dialog = builder.create();
dialog.show();
}
}
幾個關鍵點:
DatePicker.getMonth() 要 +1。它回傳的是 0-based 的月份(0 = 一月),而 Calendar.MONTH 也是 0-based,但 init() 時傳入的是 1-based 的月份。這兩個 API 的月份基準不一致,是最容易寫錯的地方。
timePicker.setIs24HourView(true) 關閉 12/24 小時切換,避免使用者選出「下午 3 點」卻被存成 15 或 3 的歧義。
String.format("%02d-%02d", ...) 統一格式化。不這麼做的話,時間會顯示成 "9-5 8:3" 這種參差的字串,後續用字串比較大小也會出錯——因為 "10-01" 的字典序小於 "9-01"。這點在下面的驗證方法中至關重要。
// 刷新並判斷開始時間與結束時間的大小
public void showTimeErrorTip() {
// 若時間不合法則提示
if (sp.getString("startTime", "").compareTo(sp.getString("endTime", "")) > 0) {
Toast.makeText(SettingActivity.this, "結束時間必須大於開始時間", 1000).show();
}
}
這裡用字串 compareTo 比大小之所以可行,正是因為前面用 %02d 做了零填充——等寬的數字字串,字典序恰好等於數值序。若時間格式是 "9:5" 而非 "09:05",這個比較就會出錯。這是一個「格式統一」換取「比較簡化」的典型交易。
不過要留意這個驗證只提示不阻擋,使用者仍可以存進不合法的區間。更嚴謹的做法是在確定前把字串解析回 Calendar 才是真正的比較,並在該筆設定不合法時拒絕保存。
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:text="選擇日期"
android:textSize="15sp" />
<DatePicker
android:id="@+id/data_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:singleLine="true"
android:text="選擇時間"
android:textSize="15sp" />
<TimePicker
android:id="@+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
兩個 Picker 垂直排列,中間用 TextView 當分隔標題,最簡單也最清楚。
設定層到這裡就完整了:開關狀態、模式選擇、起訖時間全部能存能讀。真正的攔截行為要等 Service 完成後,在監聽到來電時比對當前時間是否落在 startTime 與 endTime 之間,決定要不要掛斷。
那個時間比對有個需要小心的地方:跨日的時間區間。若使用者設 22:00 到 06:00,簡單的「起始 <= 現在 <= 結束」判斷會永遠為 false,必須額外判斷 if (start > end) 則改成 OR 邏輯。這類邊界情況在實作 Service 時要一併處理。
Java 記憶體映射檔案原理與效能解析
什麼是記憶體映射檔案記憶體映射檔案,英文常稱為 memory-mapped file,是一種把檔案內容對應到進程位址空間的機制。開發者可以像操作記憶體一樣操作檔案,而不需
自定義 Dialog 引發的問題排查實錄
我習慣從實際工作中取材。最近需要在相機裡加入聲控拍照(語音拍照)功能,在設定頁面中要實現如下效果: 這個「語音拍照」菜單的需求如下: (1) 點擊「語音拍照」菜單時彈出
RecyclerView 下拉刷新與上拉加載更多
在資訊串流或內容列表中,下拉刷新與上拉加載更多是非常常見的功能。若使用 RecyclerView,可以搭配成熟的下拉刷新套件,再自行處理 Header、Footer 與
Android 與設計模式:組合(Composite)模式入門
定義(GoF《設計模式》):將物件組合成樹形結構,以表示「部分—整體」的層次結構。組合模式使得使用者對「單個物件」和「組合物件」的使用具有一致性。 一句話理解:它讓你把「