澄清:我不想让设备保持唤醒状态,我只想在每次打开屏幕时执行我的命令。
我为什么要这样做的简短背景
一些 Oneplus One 手机有一个令人讨厌的错误,即触摸屏在一段时间后或多或少地无响应。以 root 身份运行cat /sys/class/input/input0/baseline_test可以暂时改善这种情况,至少对于某些用户而言。由于手机处于睡眠模式时通常会出现问题,因此很难解锁手机。所以,我想在每次激活手机屏幕时运行这个命令。
是的,我知道,我可以用 Tasker 做到这一点,但其中的乐趣在哪里?:)
所以,对于我的问题
我不是 android 开发人员,但我已经能够编写一个应用程序来做到这一点。它工作得很好,大约一个小时左右,之后它就停止工作了。我在代码中注册了 ACTION_SCREEN_ON 意图,因为由于某种原因,它不可能在清单中执行此操作。所以,我希望是简单的问题,我应该如何修改我的应用程序,以便它不会在后台停止。服务会帮助我吗?
我的代码:
import ...;
public class ConfigurationActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_configuration);
registBroadcastReceiver();
}
public void onDestroy(Bundle savedInstanceState) {
unregisterReceiver();
}
private BroadcastReceiver mPowerKeyReceiver = null;
private void registBroadcastReceiver() {
final IntentFilter theFilter = new IntentFilter();
theFilter.addAction(Intent.ACTION_SCREEN_ON);
mPowerKeyReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String strAction = intent.getAction();
if (strAction.equals(Intent.ACTION_SCREEN_ON)) {
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
String[] commands = {"cat /sys/class/input/input0/baseline_test"};
RunAsRoot(commands);
v.vibrate(25);
}
}
};
getApplicationContext().registerReceiver(mPowerKeyReceiver, theFilter);
}
private void unregisterReceiver() {
getApplicationContext().unregisterReceiver(mPowerKeyReceiver);
mPowerKeyReceiver = null;
}
public void RunAsRoot(String[] cmds){
Process p = null;
try {
p = Runtime.getRuntime().exec("su");
} catch (IOException e) {
e.printStackTrace();
}
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
try {
os.writeBytes(tmpCmd+"\n");
os.writeBytes("exit\n");
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}