android 模拟back键

From:http://blog.csdn.net/winson_jason/article/details/9125019
主要是在使用Fragment时能够返回前一级,所以才找到了这些资料。

有两种方式可以实现,直接上代码

方法1:

public void onBack(){
  new Thread(){
   public void run() {
    try{
     Instrumentation inst = new Instrumentation();
     inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
    }
    catch (Exception e) {
                 Log.e("Exception when onBack", e.toString());
             }
   }
  }.start();

}

注意该方法不能放在主线程中,否则会报错。



方法2:

try{
   Runtime runtime=Runtime.getRuntime();
   runtime.exec("input keyevent " + KeyEvent.KEYCODE_BACK);
  }catch(IOException e){
    Log.e("Exception when doBack", e.toString());
  }



总结:方法1比方法2响应快些。

猜你喜欢

转载自sunj.iteye.com/blog/1915554