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

撥號盤輸入密文彈出設定介面:framework 分析與完整實作

編輯:關於 Android 程式設計

這是一個常見的系統客製需求:使用者在撥號盤輸入一段特定的密文(例如 #*46825562*#),系統不撥號,而是彈出一個自訂的設定或調試介面。這個功能無法純靠 App 層完成,必須理解 framework 中撥號廣播的處理流程。

先搞清楚 framework 那邊發生了什麼

當你按下撥號鍵,系統會啟動 OutgoingCallBroadcaster。它的 onCreate() 中有這幾行關鍵程式碼:

mPhone = PhoneApp.getInstance().phone;
Intent intent = getIntent();
if (LOGV) Log.v(TAG, "onResume: Got intent " + intent + ".");
String action = intent.getAction();
String number = PhoneNumberUtils.getNumberFromIntent(intent, this);

也就是說,不管你在撥號盤輸入了什麼,號碼都會被完整取出,並放進變數 number 裡。接著它會發送一個 Intent.ACTION_NEW_OUTGOING_CALL 的序向廣播,讓外部有機會攔截:

broadcastIntent.putExtra(EXTRA_ALREADY_CALLED, callNow);
broadcastIntent.putExtra(EXTRA_ORIGINAL_URI, intent.getData().toString());
if (LOGV) Log.v(TAG, "Broadcasting intent " + broadcastIntent + ".");
sendOrderedBroadcast(broadcastIntent, PERMISSION, null, null,
        Activity.RESULT_OK, number, null);

注意最後一個參數:號碼被放進了序向廣播的 resultData,接收端可以用 getResultData() 或 getStringExtra(Intent.EXTRA_PHONE_NUMBER) 取得。

廣播跑完之後,OutgoingCallBroadcaster 內部的 OutgoingCallReceiver 會在 onReceive() 中取出原始 URI:

originalUri = intent.getStringExtra(OutgoingCallBroadcaster.EXTRA_ORIGINAL_URI);

然後啟動通話畫面:

Intent newIntent = new Intent(Intent.ACTION_CALL, uri);
newIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
newIntent.setClass(context, InCallScreen.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(newIntent);

思路:攔在 InCallScreen 之前

看完這段原始碼,答案就浮現了:既然 framework 在啟動 InCallScreen 之前會先送出一個序向廣播,那我們只要在廣播中判斷號碼,若是密文就啟動自己的介面、並把廣播結果清空,通話流程自然不會繼續。OutgoingCallBroadcaster 的 onCreate 由系統自行呼叫,我們不需要去動它,只要在外部寫一個廣播接收器加上自己的業務畫面。

步驟一:建立廣播接收器

package com.huawei.test;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

// 支援在撥號盤輸入密文,例如 #*46825562*# 彈出設定介面
public class TransferToDebugMode extends BroadcastReceiver {

    private static final String TAG = "TransferToDebugMode";

    private static final String ACTION_DEBUGMODE = "com.huawei.test.DebugModeActivity";

    // 是否啟用 Debug 模式入口,預設 true,建議改為系統級變數
    private boolean isNeedDebugModeOpen = true;

    // 觸發密文,建議改為系統變數以便調整
    private final String DebugModeOpenCode = "#*46825562*#";

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)) {
            String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
            Log.v(TAG, "Received intent " + intent + " (number = " + number + ")");

            if (isNeedDebugModeOpen && number.equals(DebugModeOpenCode)) {
                Intent newIntent = new Intent(ACTION_DEBUGMODE);
                newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(newIntent);
                setResultData(null);   // 關鍵:清空廣播結果,中斷後續撥號流程
            }
        }
    }
}

setResultData(null) 這一行是整個功能的樞紐。序向廣播的接收者可以改寫 resultData 並把結果往下游傳;清空之後,後續的接收者拿不到有效號碼,InCallScreen 就不會被啟動。

步驟二:實作設定畫面

package com.huawei.test;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

// 依系統需要,可能需繼承 HotalkActivity 或實作其他系統介面
public class DebugModeActivity extends Activity implements View.OnClickListener {

    private final String TAG = "DebugModeActivity";

    private RelativeLayout logSetting, smsLogSetting;
    private Button submit, cancle;

    // 進度視窗,可依需求移除
    private ProgressDialog pgsDialog;

    // 各項開關,預設 false
    private boolean isNeedRecord = false;
    private boolean isSmsNeedMonitor = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.debug_mode_layout);
        initView();
        addListener();
    }

    // 介面初始化
    private void initView() {
        logSetting = (RelativeLayout) findViewById(R.id.log_setting);
        smsLogSetting = (RelativeLayout) findViewById(R.id.sms_log_setting);
        submit = (Button) findViewById(R.id.debug_mode_layout_submit);
        cancle = (Button) findViewById(R.id.debug_mode_layout_cancle);
    }

    // 註冊監聽
    private void addListener() {
        logSetting.setOnClickListener(this);
        smsLogSetting.setOnClickListener(this);
        submit.setOnClickListener(this);
        cancle.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.log_setting:
                isNeedRecord = true;
                break;
            case R.id.sms_log_setting:
                isSmsNeedMonitor = true;
                break;
            case R.id.debug_mode_layout_submit:
                showProgressDialog();
                // ServerInfo.LOG_ENABLE_ON_RELEASE = isNeedRecord;
                // LogX.refreshNeedRecord();
                // LoginInfo.setMessageMonitorOpen(isSmsNeedMonitor);
                finish();
                break;
            case R.id.debug_mode_layout_cancle:
                isNeedRecord = false;
                isSmsNeedMonitor = false;
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (pgsDialog != null) {
            pgsDialog.dismiss();
        }
    }

    private void showProgressDialog() {
        pgsDialog = new ProgressDialog(DebugModeActivity.this);
        pgsDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        pgsDialog.setMessage("請稍候……");
        pgsDialog.show();
    }
}

原本範例中的 switch 每個 case 都沒有 break,會一路往下穿透執行——這通常是刻意安排(例如「按確定」時把前面設定的開關一起套用),但極易造成誤解與 Bug。上面已補上 break,並把確定/取消都導向 finish(),讓流程清楚可讀。

步驟三:版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:background="@color/card_setting_group"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:layout_width="wrap_content">

    <RelativeLayout
        android:id="@+id/title_layout"
        android:layout_width="fill_parent"
        android:layout_height="46dip"
        android:visibility="visible"
        android:background="@drawable/bg_top_bar">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginLeft="6dip"
            android:singleLine="true"
            style="@style/title_style"
            android:text="Debug Mode Setting" />
    </RelativeLayout>

    <LinearLayout
        android:layout_width="fill_parent"
        android:orientation="vertical"
        android:paddingLeft="10dip"
        android:paddingRight="10dip"
        android:layout_height="fill_parent">

        <!-- Debug 模式設置 -->
        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_marginBottom="2dip"
            android:layout_height="wrap_content"
            android:layout_marginTop="12dip">
            <TextView
                android:id="@+id/TextView02"
                android:layout_alignParentLeft="true"
                android:text="日誌設置"
                android:layout_marginLeft="12dip"
                style="@style/setting_item_title_style"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content">
            </TextView>
        </RelativeLayout>

        <RelativeLayout
            android:layout_width="fill_parent"
            android:clickable="true"
            android:focusable="true"
            android:gravity="center_vertical"
            android:background="@drawable/setting_list_bg"
            android:layout_height="wrap_content">

            <!-- 設置日誌是否開啟 -->
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:minHeight="54dip"
                android:id="@+id/log_setting"
                android:background="@drawable/settings_item_top_selector">
                <TextView
                    android:id="@+id/log_seting_name"
                    android:text="開啟日誌"
                    android:maxWidth="250dip"
                    style="@style/setting_item_function_style"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </TextView>
                <ImageView
                    android:id="@+id/img_log_open"
                    android:layout_width="wrap_content"
                    android:src="@drawable/ico_choose"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginRight="20dip"
                    android:layout_centerVertical="true" />
            </RelativeLayout>

            <!-- 分隔線 -->
            <View
                android:id="@+id/setting_setting_line"
                android:layout_width="fill_parent"
                android:layout_height="1.5dip"
                android:background="@drawable/list_fengexian"
                android:layout_centerVertical="true" />

            <!-- 設置簡訊日誌是否開啟 -->
            <RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_below="@id/log_setting"
                android:minHeight="54dip"
                android:id="@+id/sms_log_setting"
                android:background="@drawable/settings_item_top_selector">
                <TextView
                    android:id="@+id/sms_log_setting_name"
                    android:text="開啟簡訊日誌"
                    android:maxWidth="250dip"
                    style="@style/setting_item_function_style"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content">
                </TextView>
                <ImageView
                    android:id="@+id/img_open_sms_log"
                    android:layout_width="wrap_content"
                    android:src="@drawable/ico_choose"
                    android:layout_height="wrap_content"
                    android:layout_alignParentRight="true"
                    android:layout_marginRight="20dip"
                    android:layout_centerVertical="true" />
            </RelativeLayout>
        </RelativeLayout>>

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="50dip"
            android:layout_marginTop="15dip"
            android:padding="10dp"
            android:gravity="center">

            <Button
                android:id="@+id/debug_mode_layout_submit"
                style="@style/invite_cancel_button_style"
                android:layout_width="95dip"
                android:layout_height="36dip"
                android:layout_marginRight="45dip"
                android:background="@drawable/cancle_button"
                android:text="確定" />

            <Button
                android:id="@+id/debug_mode_layout_cancle"
                style="@style/invite_cancel_button_style"
                android:layout_width="95dip"
                android:layout_height="36dip"
                android:background="@drawable/cancle_button"
                android:text="取消" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

步驟四:Manifest 註冊與權限

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.huawei.test"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:enabled="true">

        <activity android:name="com.huawei.test.DebugModeActivity">
            <intent-filter>
                <action android:name="com.huawei.test.DebugModeActivity"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </activity>

        <receiver android:name="com.huawei.test.TransferToDebugMode" >
            <intent-filter android:priority="0">
                <action android:name="android.intent.action.NEW_OUTGOING_CALL"/>
                <category android:name="android.intent.category.DEFAULT"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

PROCESS_OUTGOING_CALLS 權限是必須的,否則接收器永遠收不到廣播。android:priority 決定序向廣播中的先後順序,數值越大越早收到;如果你的密文要搶在其他攔截者之前處理,就需要提高 priority。

幾個實務上的坑

密文要夠長夠怪。序向廣播是可被任何 App 攔截的,若密文太短或太常見(例如 #*#123#*#),可能與其他應用或系統功能衝突。實務上建議使用一組足夠長、不易撞號的數字。

務必清空結果。忘了呼叫 setResultData(null) 是最常見的失敗原因——畫面跳出來了,但撥號也照樣進行,使用者同時看到設定頁與通話頁。

這個入口等於後門。能開啟日誌、監控簡訊的隱藏介面,若沒有任何保護,任何人拿到裝置都能開啟。請至少加上條件判斷(例如只在 debug 版本註冊此 receiver),正式版本請用 android:enabled 或 build variant 關閉。

這些都是系統客製情境。本方案依賴 framework 的 OutgoingCallBroadcaster 行為,且 PROCESS_OUTGOING_CALLS 屬於簽名級權限,一般第三方應用程式無法取得。它適用於你正在客製 ROM 或平台版本的情況;若是一般上架的 App,請改用 ACTION_SECRET_CODE 廣播機制,那是官方為密文入口保留的公開途徑。

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