发送命令模拟按键操作
方法一:
/*** 用Runtime模拟按键操作** @param keyCode 按键事件(KeyEvent)的按键值*/private void sendKeyCode1(int keyCode) {try {String keyCommand = "input keyevent " + keyCode;// 调用Runtime模拟按键操作Runtime.getRuntime().exec(keyCommand);} catch (Exception e) {e.printStackTrace();}}
方法二 :
/*** 使用Instrumentation接口:对于非自行编译的安卓系统,无法获取系统签名,只能在前台模拟按键,不能后台模拟* 注意:调用Instrumentation的sendKeyDownUpSync方法必须另起一个线程,否则无效* @param keyCode 按键事件(KeyEvent)的按键值*/private void sendKeyCode2(final int keyCode) {new Thread(new Runnable() {@Overridepublic void run() {try {// 创建一个Instrumentation对象Instrumentation inst = new Instrumentation();// 调用inst对象的按键模拟方法inst.sendKeyDownUpSync(keyCode);} catch (Exception e) {e.printStackTrace();}}}).start();}
退出了应用之后内存还是占用着的,但是每次进来app都要重新加载一边数据,看了看微信,QQ等其它的一些大的App都没有正常的退出App,而是模拟了Home键按下效果。
Intent intent = new Intent(Intent.ACTION_MAIN);intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);intent.addCategory(Intent.CATEGORY_HOME);startActivity(intent);