I am making an app with the Host mode enabled. Now my problem is i need to make device go to sleep mode on idle condition of my app.
Some Points:
So, I need to do force sleep after specific time or fire an even from a button click. Thanks in advance, friends.
Finally I solved this.
This class will goto sleep/display off after predefined time.
public class MainActivity extends Activity {
public static final long DISCONNECT_TIMEOUT = 10000; // 10 sec, time to go sleep
protected static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private Runnable disconnectCallback = new Runnable() {
@Override
public void run() {
Log.d(TAG, "++++Idle State End");
Toast.makeText(getApplicationContext(), "Going to Sleep Mode", 0).show();
goToSleep();
}
};
//Display off
public void goToSleep() {
try {
// REQUIRES ROOT
Process proc;
proc = Runtime.getRuntime().exec("su", null, null);
OutputStream os = proc.getOutputStream();
os.write(("sendevent /dev/input/event1 1 116 1; sendevent /dev/input/event1 0 0 0; sendevent /dev/input/event1 1 116 0; sendevent /dev/input/event1 0 0 0;")
.getBytes("ASCII"));
os.flush();
os.close();
// 79
proc.waitFor();
} catch (Exception ex) {
}
}
private Handler disconnectHandler = new Handler() {
public void handleMessage(Message msg) {
Log.d(TAG, "++++disconnectHandler");
}
};
public void resetDisconnectTimer() {
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer() {
disconnectHandler.removeCallbacks(disconnectCallback);
}
@Override
public void onUserInteraction() {
resetDisconnectTimer();
}
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "onResume");
resetDisconnectTimer();
}
@Override
public void onStop() {
super.onStop();
stopDisconnectTimer();
}
}
I hope my answer will reference for someone else.