1 在AndroidManifest.xml中添加:
<receiver android:name="com.android.settings.MyReceiver" >
<intent-filter>
<action android:name="android.provider.Telephony.SECRET_CODE" />
<data android:host="1234567" android:scheme="android_secret_code" />
</intent-filter>
</receiver>
其中android:host=“1234567” 设置暗码
2 新建一个广播接收的类
public class MyReceiver extends BroadcastReceiver {
private final String TAG = "MyReceiver";
Uri engineerUri = Uri.parse("android_secret_code://1234567");
@Override
public void onReceive(Context context, Intent intent) {
try {
if (intent.getAction().equals("android.provider.Telephony.SECRET_CODE")) {
Uri uri = intent.getData();
if (uri.equals(engineerUri)) {
// TODO 这里处理相关事情
}
}
}
}
}
分析
/packages/apps/Dialer/java/com/android/dialer/app/SpecialCharSequenceMgr.java
static boolean handleSecretCode(Context context, String input) {
// Secret codes are accessed by dialing *#*#<code>#*#*
int len = input.length();
if (len <= 8 || !input.startsWith("*#*#") || !input.endsWith("#*#*")) {
return false;
}
String secretCode = input.substring(4, len - 4);
TelephonyManagerCompat.handleSecretCode(context, secretCode);
return true;
}
handleSecretCode方法对输入的暗码进行解析,然后执行TelephonyManagerCompat.handleSecretCode方法。
/packages/apps/Dialer/java/com/android/contacts/common/compat/TelephonyManagerCompat.java
private static final String SECRET_CODE_ACTION = "android.provider.Telephony.SECRET_CODE";
public static void handleSecretCode(Context context, String secretCode) {
// Must use system service on O+ to avoid using broadcasts, which are not allowed on O+.
if (BuildCompat.isAtLeastO()) {
if (!TelecomUtil.isDefaultDialer(context)) {
LogUtil.e(
"TelephonyManagerCompat.handleSecretCode",
"not default dialer, cannot send special code");
return;
}
context.getSystemService(TelephonyManager.class).sendDialerSpecialCode(secretCode);
} else {
// System service call is not supported pre-O, so must use a broadcast for N-.
Intent intent =
new Intent(SECRET_CODE_ACTION, Uri.parse("android_secret_code://" + secretCode));
context.sendBroadcast(intent);
}
}
此方法通过发送一条SECRET_CODE_ACTION,并携带Uri数据形式的广播,把消息传播出去。