设备在日常使用过程中,不可避免的会添加安装第三方应用。但并不是每一个应用都是安全的,对系统无伤害的。由于第三方应用程序,可能会存在一定的兼容性问题,所以在安装软件后可能会出现系统文件报错,甚至手机无法正常开机或者开机后系统程序不停报错的现象。遇到这种情况,若进行恢复出厂设置,手机中的资料是无法进行备份的,但是Android系统中添加了"安全模式"这项功能,有效的避免上述情况同时来排除故障。
流程:
设备在启动到systemServer后,会在systemServer中进行安全模式的检测:
\frameworks\base\services\java\com\android\server\SystemServer.java
SystemServer.java
private void startOtherServices() {
// Before things start rolling, be sure we have decided whether
// we are in safe mode.
final boolean safeMode = wm.detectSafeMode();
if (safeMode) {
mActivityManagerService.enterSafeMode();
// Disable the JIT for the system_server process
VMRuntime.getRuntime().disableJitCompilation();
} else {
// Enable the JIT for the system_server process
VMRuntime.getRuntime().startJitCompilation();
}
}
这里system server分两个步骤进行:检测安全模式detectSafeMode()和进入安全模式enterSafeMode()。
这里只看检测部分:
\frameworks\base\services\core\java\com\android\server\wm\WindowManagerService.java
WindowManagerService.java
public boolean detectSafeMode() {
if (!mInputMonitor.waitForInputDevicesReady(
INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS)) {
Slog.w(TAG, "Devices still not ready after waiting "
+ INPUT_DEVICES_READY_FOR_SAFE_MODE_DETECTION_TIMEOUT_MILLIS
+ " milliseconds before attempting to detect safe mode.");
}
int menuState = mInputManager.getKeyCodeState(-1, InputDevice.SOURCE_ANY, KeyEvent.KEYCODE_MENU);
int sState = mInputManager.getKeyCodeState(-1, InputDevice.SOURCE_ANY, KeyEvent.KEYCODE_S);
int dpadState = mInputManager.getKeyCodeState(-1, InputDevice.SOURCE_DPAD, KeyEvent.KEYCODE_DPAD_CENTER);
int trackballState = mInputManager.getScanCodeState(-1, InputDevice.SOURCE_TRACKBALL, InputManagerService.BTN_MOUSE);
int volumeDownState = mInputManager.getKeyCodeState(-1, InputDevice.SOURCE_ANY, KeyEvent.KEYCODE_VOLUME_DOWN);
mSafeMode = menuState > 0 || sState > 0 || dpadState > 0 || trackballState > 0 || volumeDownState > 0;
try {
if (SystemProperties.getInt(ShutdownThread.REBOOT_SAFEMODE_PROPERTY, 0) != 0) {
mSafeMode = true;
SystemProperties.set(ShutdownThread.REBOOT_SAFEMODE_PROPERTY, "");
}
} catch (IllegalArgumentException e) {
}
if (mSafeMode) {
Log.i(TAG, "SAFE MODE ENABLED (menu=" + menuState + " s=" + sState
+ " dpad=" + dpadState + " trackball=" + trackballState + ")");
} else {
Log.i(TAG, "SAFE MODE not enabled");
}
mPolicy.setSafeMode(mSafeMode);
return mSafeMode;
}
通过分析上述代码可知,系统在这里对5个键值进行了扫描:菜单键menuState、s键sState、dpad中间键dpadState、轨迹球trackballState以及音量减键volumeDownState。其中有一个被检测到,则会将安全模式唯一的全局变量标识SafeMode设为true。往下看,在try阶段,系统会获取ShutdownThread.REBOOT_SAFEMODE_PROPERTY prop项的值,如果该值存在,则也将mSafeMode设为true。这里也许会比较奇怪,为何通过按键值设置完mSafeMode后还需要检测下REBOOT_SAFEMODE_PROPERTY prop项?其实这里是为了系统在正常模式下重启后进入安全模式准备的。系统通过正常模式进入到安全模式前,会将REBOOT_SAFEMODE_PROPERTY prop项的值设为1,这里既是上述5个按键没有一个按下也可以进安全模式。具体代码位置如下:
ShutdownThread.java
public void run() {
...
/*
* If we are rebooting into safe mode, write a system property
* indicating so.
*/
if (mRebootSafeMode) {
SystemProperties.set(REBOOT_SAFEMODE_PROPERTY, "1");
}
}