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

來電管家實作(七):載入使用者設定並啟動監聽服務

編輯:關於 Android 程式設計

使用者設定以 SharedPreferences 保存。首次進入時寫入一組預設值,之後則依使用者的操作更新對應內容。

應用啟動後第一個進入的是 ActivityGroupDemo,預設顯示黑名單頁。因此判斷是否為首次啟動的邏輯,就寫在這裡。

一、判斷是否首次啟動

思路很樸素:

  1. SharedPreferences 會在應用目錄下的 shared_prefs/ 資料夾產生對應的 XML 檔。
  2. 每次啟動時檢查該檔案是否存在,不存在即代表使用者是第一次進入。
  3. 若為首次,寫入各項預設設定。

先在 ActivityGroupDemo 中宣告:

private SharedPreferences spf;

接著在合適的初始化時機寫入預設值:

spf = this.getSharedPreferences("setting", Activity.MODE_PRIVATE);
SharedPreferences.Editor editor = spf.edit();

// 取出當前應用的檔案路徑
String path = this.getFilesDir().toString();
// 拼出 shared_prefs/setting.xml
path = path.substring(0, path.lastIndexOf("/") + 1);
path += "shared_prefs/setting.xml";

// 以檔案是否存在判斷是否首次啟動
File file = new File(path);
if (!file.exists()) {
    editor.putBoolean("isStartListen", false);  // 預設不啟用監聽
    editor.putBoolean("isWhiteList", false);    // 預設黑名單模式
    editor.putBoolean("isTime", false);         // 預設不啟用時段攔截
    editor.putString("startTime", null);
    editor.putString("endTime", null);
    editor.commit();
}

順帶一提,用 File 是否存在來判斷首次啟動雖然直觀,但並不是最穩健的做法。更可靠的方式是存一個 putBoolean("firstRun", false) 的旗標,因為設定檔的路徑與名稱在後續重構時有可能變動。

二、把設定回讀到介面

若不保存設定,使用者下次打開設定頁看到的會是程式內寫死的預設值,而非他上次的選擇。要讓設定具備延續性,就必須在進入設定頁時把存的值讀出來並套用。

主要兩步:在 SettingActivity 的 onCreate 中讀取設定檔,再把讀到的值套用到介面元件。程式碼如下:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_setting);
    // ... 其他初始化
    loadSetting();
}

/** 讀取設定並套用到介面 */
public void loadSetting() {
    loadSettingImage(tb_switch, sp.getBoolean("isStartListen", false));
    loadSettingImage(tb_whiteList, sp.getBoolean("isWhiteList", false));
    loadSettingImage(tb_time, sp.getBoolean("isTime", false));

    tb_switch.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
    tb_whiteList.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
    tb_time.setOnCheckedChangeListener(new ToggleButtonCheckedEvent());
}

/** 依設定值配置控制項外觀與連動狀態 */
public void loadSettingImage(View v, boolean isChecked) {
    switch (v.getId()) {
        case R.id.tb_switch:
            tb_switch.setChecked(isChecked);
            if (isChecked) {
                tb_switch.setBackgroundResource(R.drawable.start_service_on);
                getApplicationContext().startService(intent);
            } else {
                tb_switch.setBackgroundResource(R.drawable.start_service_off);
            }
            break;

        case R.id.tb_whitelist:
            tb_whiteList.setChecked(isChecked);
            tb_whiteList.setBackgroundResource(isChecked
                    ? R.drawable.start_service_on
                    : R.drawable.start_service_off);
            break;

        case 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);
                tv_start_time.setText(sp.getString("startTime", ""));
                tv_end_time.setText(sp.getString("endTime", ""));
            } 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);
                String[] time = getCurrentTime();
                tv_start_time.setText(time[0]);
                tv_end_time.setText(time[1]);
            }
            break;
    }
}

這樣一來,設定畫面的呈現就會隨使用者先前的選擇而變化。

三、以服務的啟停控制攔截

前幾節已完成依規則攔截來電的能力,剩下的是「何時開始攔、何時停止」。答案就在設定頁第一項的「啟用攔截」開關。

啟動服務需要 Intent,並且要指定 action。在 onCreate 中先建立:

Intent intent;
// ...
intent = new Intent("com.example.callmanager.ListenService");

開關被開啟時啟動服務:

// 啟用服務
getApplicationContext().startService(intent);

開關被關閉時停止服務:

// 關閉服務
getApplicationContext().stopService(intent);

至此,載入使用者設定與啟停監聽服務就完成了。

四、一個實作上的提醒

設定頁與 Service 之間目前靠 SharedPreferences 單向溝通:Service 每次回電狀態改變時才去讀設定,因此改動會即時生效,這沒問題。但要注意 startService/stopService 必須在使用者主動切換時呼叫,若放在 onCreate 的載入流程裡,每次進入設定頁都會重新觸發一次。實務上建議只在 onCheckedChanged 回呼中處理服務啟停,載入階段則僅同步 UI 狀態,並額外判斷服務是否已在執行。

另外,Android 8.0 之後背景啟動服務的限制會讓這類設計失效,需改用 startForegroundService 並搭配通知列;來電攔截本身也建議遷移到 CallScreeningService,這是官方提供的正式 API。

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