当前位置: 代码迷 >> Android >> Android 兑现Activity后台运行(转)
  详细解决方案

Android 兑现Activity后台运行(转)

热度:48   发布时间:2016-05-01 20:50:34.0
Android 实现Activity后台运行(转)

?

Android 实现Activity后台运行

    博客分类:?
  • android
Android

第一种方法

?

Java代码??收藏代码
  1. Intent?intent?=?new?Intent(Intent.ACTION_MAIN);??
  2. intent.addCategory(Intent.CATEGORY_HOME);??
  3. intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);??
  4. startActivity(intent);??

?

?

第二种方法

?

此方法其实不是主要是屏蔽Keycode_Back,让它不结束(finish())Activity,直接显示HOME界面。

?

Java代码??收藏代码
  1. PackageManager?pm?=?getPackageManager();??
  2. ??????????????????????????????ResolveInfo?homeInfo?=?pm.resolveActivity(new?Intent(Intent.ACTION_MAIN)??
  3. .addCategory(Intent.CATEGORY_HOME),?0);??

?

?

Java代码??收藏代码
  1. public?boolean?onKeyDown(int?keyCode,?KeyEvent?event)?{??
  2. ????if?(keyCode?==?KeyEvent.KEYCODE_BACK)?{??
  3. ????????ActivityInfo?ai?=?homeInfo.activityInfo;??
  4. ????????Intent?startIntent?=?new?Intent(Intent.ACTION_MAIN);??
  5. ????????startIntent.addCategory(Intent.CATEGORY_LAUNCHER);??
  6. ????????startIntent.setComponent(new?ComponentName(ai.packageName,??
  7. ????????????????ai.name));??
  8. ????????startActivitySafely(startIntent);??
  9. ????????return?true;??
  10. ????}?else??
  11. ????????return?super.onKeyDown(keyCode,?event);??
  12. }??

?

?

Java代码??收藏代码
  1. void?startActivitySafely(Intent?intent)?{??
  2. ????intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);??
  3. ????try?{??
  4. ????????startActivity(intent);??
  5. ????}?catch?(ActivityNotFoundException?e)?{??
  6. ????????Toast.makeText(this,?R.string.unabletoopensoftware,??
  7. ????????????????Toast.LENGTH_SHORT).show();??
  8. ????}?catch?(SecurityException?e)?{??
  9. ????????Toast.makeText(this,?R.string.unabletoopensoftware,??
  10. ????????????????Toast.LENGTH_SHORT).show();??
  11. ????????Log??
  12. ????????????????.e(??
  13. ????????????????????????TAG,??
  14. ????????????????????????"Launcher?does?not?have?the?permission?to?launch?"??
  15. ????????????????????????????????+?intent??
  16. ????????????????????????????????+?".?Make?sure?to?create?a?MAIN?intent-filter?for?the?corresponding?activity?"??
  17. ????????????????????????????????+?"or?use?the?exported?attribute?for?this?activity.",??
  18. ????????????????????????e);??
  19. ????}??
  20. }??

?

  相关解决方案