开发者

Android back key by software

开发者 https://www.devze.com 2023-03-01 08:25 出处:网络
Dows anybody know how I can simulate pressing the back key by software? I开发者_运维技巧\'ve seen some applications which simulate this key and a few other keys like home and search. But because thees

Dows anybody know how I can simulate pressing the back key by software? I开发者_运维技巧've seen some applications which simulate this key and a few other keys like home and search. But because theese weren't open source, I tried to build my own application which can manage theese tasks. To go back to home for example is very easy because I had to send just one intent. So... what can I do to simulate the back key? :)

UPDATE:

I've downloaded an open source application which has the same functions from http://git.hoopajoo.net/

There it's done like that:

Process process = Runtime.getRuntime().exec("su");
OutputStream outputStream = process.getOutputStream();
String cmd = "keycode " + KeyEvent.KEYCODE_BACK;
outputStream.write((cmd + "\n").getBytes("ASCII"));

Where does the "keycode" command come from? I could not found any so called binary in my Android rootfs?!?!


Aleadam method don't work on my android 4.1.2. I don't know why, but this workaround works:

public void dispachBackKey() {
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
    dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));
}


To simulate a key press, you can dispatch a KeyEvent:

myView.getRootView().dispatchKeyEvent(new KeyEvent (KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));

An alternative solution for this situation is to have an ongoing notification (see http://developer.android.com/reference/android/app/NotificationManager.html ) that will stop the service when clicked.


I had exactly the same problem as you. Turns out the syntax of commands in runCommand used by SoftKeys is different from the shell.

In shell to emulate key event, use input keyevent. Looking up the documentation, key code for back button () is 4. So do this:

input keyevent 4

http://forum.xda-developers.com/showthread.php?t=971768

http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_BACK


You should call the onKeyDown() function. THe keycode isn't hard to get, but you might need to do something to give a sane event.

0

精彩评论

暂无评论...
验证码 换一张
取 消