</pre><pre name="code" class="java"> /** * 改写返回键事件监听,使得back键功能类似home键,让Acitivty退至后台时不被系统销毁 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { PackageManager pm = getPackageManager(); ResolveInfo homeInfo = pm.resolveActivity( new Intent(Intent.ACTION_MAIN) .addCategory(Intent.CATEGORY_HOME), 0); if (keyCode == KeyEvent.KEYCODE_BACK) { ActivityInfo ai = homeInfo.activityInfo; Intent startIntent = new Intent(Intent.ACTION_MAIN); startIntent.addCategory(Intent.CATEGORY_LAUNCHER); startIntent .setComponent(new ComponentName(ai.packageName, ai.name)); startActivitySafely(startIntent); return true; } else return super.onKeyDown(keyCode, event); } private void startActivitySafely(Intent intent) { intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); try { startActivity(intent); } catch (ActivityNotFoundException e) { Toast.makeText(this, "null", Toast.LENGTH_SHORT).show(); } catch (SecurityException e) { Toast.makeText(this, "null", Toast.LENGTH_SHORT).show(); } }
原文地址:http://blog.csdn.net/yybj/article/details/42126139