Search code examples
androidawtrobot

How to press physical buttons of android programatically


I want to press volume button programatically. In Java it is possible using the robot class, but in Android there is no robot class.

I am wondering how to achieve this in Android.


Solution

  • I would suggest you to increase/decrease the volume programmatically which would be a tad bit easier, however if you want to use it for some other process then you can check the code below - EDIT - The snippet I gave before doesn't work, but this one does. It uses a runnable so the try catch block is necessary.

     new Thread(new Runnable() {         
                @Override
                public void run() {
                    try {
                        Instrumentation inst = new Instrumentation();
                        //This is for Volume Down, change to 
                        //KEYCODE_VOLUME_UP for Volume Up.
                        inst.sendKeyDownUpSync(KeyEvent.KEYCODE_VOLUME_DOWN);
                    }catch(InterruptedException e){}
                }   
            }).start();