Android实现Back功能代码片段总结
实现Back键功能方法有:
一:重写onBackPressed方法
@Override
publicvoidonBackPressed(){
//dosomethingwhatyouwant
super.onBackPressed();
}
二:使用测试框架Instrumentation,模拟任意键按下动作,注意的是该方法不能在主线程中使用,只能开启新线程,带来的问题就是反应速度较慢,项目中不建议使用。
调用onBack()方法;产生back键单击效果
publicvoidonBack(){
newThread(){
publicvoidrun(){
try{
Instrumentationinst=newInstrumentation();
inst.sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);
}
catch(Exceptione){
Log.e("ExceptionwhenonBack",e.toString());
}
}
}.start();
}
三:此方法是网络上搜集的,没有代码验证。
try{
Runtimeruntime=Runtime.getRuntime();
runtime.exec("inputkeyevent"+KeyEvent.KEYCODE_BACK);
}catch(IOExceptione){
Log.e("ExceptionwhendoBack",e.toString());
}
四:重写dispatchKeyEvent
@Override
publicbooleandispatchKeyEvent(KeyEventevent){
//TODOAuto-generatedmethodstub
if(event.getAction()==KeyEvent.ACTION_DOWN
&&event.getKeyCode()==KeyEvent.KEYCODE_BACK){
//dosomethingwhatyouwant
returntrue;//返回true,把事件消费掉,不会继续调用onBackPressed
}
returnsuper.dispatchKeyEvent(event);
}
五:这个方法算不上是完全意义的Back键的功能了,此方法只能关闭当前的Activity,也就是对于一个只有单个Activity的应用程序有效,如果对于有多外Activity的应用程序它就无能为力了。
publicvoidexitProgrames(){
android.os.Process.killProcess(android.os.Process.myPid());
}
使用此方法需要追加权限:<uses-permissionandroid:name="android.permission.RESTART_PACKAGES"/>