Reputation: 469
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.
Upvotes: 7
Views: 3772
Reputation: 941
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();
Upvotes: 6
Reputation: 11
how about this
private abstract class SimpleButton extends Button {
public SimpleButton(String text) {
super(TechDemoLauncher.this);
setText(text);
setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
onButtonPressed();
}
});
}
public abstract void onButtonPressed();
}
after that you can just implement the onButtonPressed() method like this
private void Example(String string) {
yourLayout.addView(new SimpleButton(string) {
@Override
public void onButtonPressed() {
//insert your code
}
});
}
Upvotes: -1