Question

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:

  • Power button will not be accessible,(as device will be fitted in some box/container )
  • USB OTG cable attached: In HOST mode, USB draws the power from the android device.
  • Power-in from adapter is slower than to power-out from OTG cable.
  • I have enabled do not sleep while charging.
  • My Android is Rooted.

So, I need to do force sleep after specific time or fire an even from a button click. Thanks in advance, friends.

Was it helpful?

Solution

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.

OTHER TIPS

Runtime.getRuntime().exec(new String[] { 
    "su", "-c", "input keyevent 26"
}).waitFor();

If your app is installed as a Device Admin, you can use something as simple as lockNow(). I assume that it can be installed that way, since it sounds like you're doing a custom kiosk/display setup.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top