【android基础】之Android返回键处理(事件)
16lz
2021-12-04
Android返回键我们经常都要进行处理,我的两个应用分别有以下两个不同的处理方式
方式一:按返回键显示退出提示框( 自定义提示框架可以参考[Android使用自定义AlertDialog(退出提示框) ] )
方式二:按返回键不退出应用,返回主页面(即与按Home键操作一样)
方式一:
public class WelcomeActivity extends Activity {public boolean onKeyDown(int keyCode, KeyEvent event) {// 如果是返回键,直接返回到桌面if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){ showExitGameAlert();
/* // 做其他处理或者跳转 if(keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME){ Intent intent = new Intent(MeimeiImageActivity.this,MeimeiImageActivity.class); startActivity(intent); return true; }else { return super.onKeyDown(keyCode, event); }*/
} return super.onKeyDown(keyCode, event);} private void showExitGameAlert() {final AlertDialog dlg = new AlertDialog.Builder(this).create();dlg.show();Window window = dlg.getWindow();window.setContentView(R.layout.shrew_exit_dialog);ImageButton ok = (ImageButton) window.findViewById(R.id.btn_ok);ok.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {exitApp();}}); ImageButton cancel = (ImageButton) window.findViewById(R.id.btn_cancel);cancel.setOnClickListener(new View.OnClickListener() {public void onClick(View v) {dlg.cancel();}});}}
方式二:
-
public class SenseSoccerScoreActivity extends Activity {public boolean onKeyDown(int keyCode, KeyEvent event) {// 如果是返回键,直接返回到桌面 // 经过测试,如果是乐Phone返回桌面会报错if(keyCode == KeyEvent.KEYCODE_BACK){// 创建退出系统提示框if(notSupportKeyCodeBack()){ new AlertDialog.Builder(this) .setMessage(this.getText(R.string.sure_exit_app).toString()) .setPositiveButton(R.string.text_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { exitApp(); // 退出应用处理 } }) .setNegativeButton(R.string.text_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).create().show();} else {// 返回桌面,经测试,有一些手机不支持,查看 notSupportKeyCodeBack 方法Intent i= new Intent(Intent.ACTION_MAIN);i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); i.addCategory(Intent.CATEGORY_HOME);startActivity(i);return false;}}return super.onKeyDown(keyCode, event);} // 经过测试,如果是乐Phone返回桌面会报错private boolean notSupportKeyCodeBack(){if("3GW100".equals(Build.MODEL) || "3GW101".equals(Build.MODEL) || "3GC101".equals(Build.MODEL)) {return true;}return false;}}
更多相关文章
- Android与H5混合开发「kotlin,WebView」
- Android和iOS自带的人脸检测API
- Android(安卓)桌面角标在各大品牌机型上的实现
- Android日常整理(一)---android返回键、Fragment、android分割线、
- Android中View的事件执行机制
- 在android用Google Geocoding API服务解析地址(关键词:android/GP
- android 2.2+ 完全退出程序的方法
- android 退出机制
- Android(安卓)MTK Launcher3 替换桌面图标