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

客製 FM 收音機:預先內建指定頻道

編輯:關於 Android 程式設計

需求情境是這樣的:希望內建五個頻道,也就是使用者燒錄軟體後第一次打開 FM,即使還沒進行搜台,頻道列表就已經能顯示這些預設台。

實作步驟

1. 在 FMRadioService.java 定義內建頻道陣列

// 自訂內建頻道,單位為 0.1 MHz
private int defaultChannels[] = new int[] {875, 903, 918, 942, 1025};

2. 於 initService() 中寫入

insertDefaultStation(defaultChannels);

3. 實作 insertDefaultStation()

這個函數會先排序頻道陣列,逐一驗證是否為合法頻率,再以批次方式寫入資料庫,最後回傳第一個有效頻道與寫入的筆數。

private int[] insertDefaultStation(int[] channels) {
    LogUtils.d(TAG, "insertDefaultStation.firstValidChannel: " + Arrays.toString(channels));

    int firstValidChannel = mCurrentStation;
    int channelNum = 0;

    if (null != channels) {
        Arrays.sort(channels);
        int size = channels.length;

        // 以批次方式將預設台寫入資料庫
        ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        String defaultStationName = getString(R.string.default_station_name);

        for (int i = 0; i < size; i++) {
            if (FMRadioUtils.isValidStation(channels[i])) {
                if (0 == channelNum) {
                    firstValidChannel = channels[i];
                }
                // 避免重複寫入同一個頻道
                if (!FMRadioStation.isDefaultStation(mContext, channels[i])) {
                    ops.add(ContentProviderOperation.newInsert(Station.CONTENT_URI)
                            .withValue(Station.COLUMN_STATION_NAME, defaultStationName)
                            .withValue(Station.COLUMN_STATION_FREQ, channels[i])
                            .withValue(Station.COLUMN_STATION_TYPE,
                                       FMRadioStation.STATION_TYPE_SEARCHED)
                            .build());
                }
                channelNum++;
            }
        }

        try {
            mContext.getContentResolver().applyBatch(FMRadioStation.AUTHORITY, ops);
        } catch (RemoteException e) {
            LogUtils.d(TAG, "Exception when applyBatch searched stations " + e);
        } catch (OperationApplicationException e) {
            LogUtils.d(TAG, "Exception when applyBatch searched stations " + e);
        }
    }

    LogUtils.d(TAG, "insertDefaultStation.firstValidChannel: " + firstValidChannel
            + ", channelNum: " + channelNum);
    return (new int[] { firstValidChannel, channelNum });
}

4. 在搜台完成後一併寫入

於 handleMessage() 的 FMRadioListener.MSGID_SCAN_FINISHED 分支中,原本呼叫 insertSearchedStation(channels) 之後,再補上一行:

insertDefaultStation(defaultChannels);

5. 在 FMRadioStation.java 加上輔助判斷

public static boolean isDefaultStation(Context context, int iStation) {
    return isStationExist(context, iStation, STATION_TYPE_SEARCHED);
}

這樣一來,不論是首次開機尚未搜台,還是使用者重新搜台之後,內建頻道都會確保存在於列表中,且不會因重複寫入而產生重複項目。

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