设置Android设备长按Power直接关机
Android4.0.3版本中长按Power按键跳出关机选项对话框;但在一些项目会需要长按Power直接关机而不是跳出关机选项对话框。Android4.0.3源码中并无长按直接关机的代码及选项,因此需要我们自己添加。
思路及实现:
参照长按Power按键跳出的关机对话框及关机流程部分代码,可以发现涉及到长按Power按键,关机及需要实现我们需要的功能的文件集中在:
framework/base/core/res/res/values/config.xml
framework/base/policy/src/com/android/internal/policy/impl/PhoneWindowManger.java
具体修改如下:
第一步:
在PhoneWindowManager.java中
添加static final int LONG_PRESS_POWER_OFF_NOW = 3;
如下:
static final int LONG_PRESS_POWER_NOTHING = 0;
static final int LONG_PRESS_POWER_GLOBAL_ACTIONS = 1;
static final int LONG_PRESS_POWER_SHUT_OFF = 2;
static final int LONG_PRESS_POWER_OFF_NOW = 3;
其中各个变量即为长按Power按键时的条件选项
然后找到mPowerLongPress ,这是个Runnable,当长按Power案件之后系统启动的线程
具体添加长按关机代码如下:
private final Runnable mPowerLongPress = new Runnable() {
public void run() {
// The context isn't read
if (mLongPressOnPowerBehavior < 0) {
mLongPressOnPowerBehavior = mContext.getResources().getInteger(
com.android.internal.R.integer.config_longPressOnPowerBehavior);
}
switch (mLongPressOnPowerBehavior) {
case LONG_PRESS_POWER_NOTHING:
break;
case LONG_PRESS_POWER_GLOBAL_ACTIONS:
mPowerKeyHandled = true;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
showGlobalActionsDialog();
break;
case LONG_PRESS_POWER_SHUT_OFF:
mPowerKeyHandled = true;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
ShutdownThread.shutdown(mContext, true);
break;
case LONG_PRESS_POWER_OFF_NOW://长按Power按键关机代码
Log.d(TAG,"-->> mPowerLongPress:run():LONG_PRESS_POWER_OFF_NOW");
mPowerKeyHandled = true;
performHapticFeedbackLw(null, HapticFeedbackConstants.LONG_PRESS, false);
sendCloseSystemWindows(SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS);
ShutdownThread.shutdown(mContext, false);
break;
}
}
};
第二步:
在第一步中我们添加了长按Power按键之后关机的处理代码,接下来需要在config.xml文件中修改默认设置,修改为默认长按直接关机。找到<integer name="config_longPressOnPowerBehavior">1</integer>
将默认的1修改为3,如下:
<!-- <integer name="config_longPressOnPowerBehavior">1</integer> -->
<integer name="config_longPressOnPowerBehavior">3</integer>
重新编译,下载版本之后,长按Power按键即可直接关机。