Clarification: I do not want to keep the device awake, I just want to execute my command everytime the screen is turned on.
Short background to why I want to do this
Some Oneplus One phones has a nasty bug where the touchscreen gets more or less unresponsive after a while. Running cat /sys/class/input/input0/baseline_test
as root improves the situation for a while, at least for some users.
Since the problems often ocures when the phone is in sleep mode, it can be very hard to unlock the phone. So, I want to run this command every time the phone screen is activated.
Yes, I know, I can do this with Tasker, but where is the fun in that? :)
So, to my problem
I am not an android developer, but I have been able to write an application that does just this. It works perfectly fine, for about an hour or so, after which it just stops working. I register the ACTION_SCREEN_ON intent in the code, since it, for some reason, is not possible to do this in the manifest. So, my hopefully simple question, how should I modify my application so that it is not stopped in the background. Would a service help me?
My code:
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();
}
}
}
}