隐藏

xamarin.android App在后台运行不退出

发布:2021/10/14 14:30:22作者:管理员 来源:本站 浏览次数:986

	
  1. /// <summary>
  2. /// 重写按键事件
  3. /// </summary>
  4. /// <param name="keyCode"></param>
  5. /// <param name="e"></param>
  6. /// <returns></returns>
  7. public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
  8. {
  9. // 根据某种情形禁用返回键
  10. if (keyCode == Keycode.Back && disableBack)
  11. {
  12. PackageManager pm = PackageManager;
  13. ResolveInfo homeInfo = pm.ResolveActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome), );
  14. ActivityInfo ai = homeInfo.ActivityInfo;
  15. Intent startIntent = new Intent(Intent.ActionMain);
  16. startIntent.AddCategory(Intent.CategoryLauncher);
  17. startIntent.SetComponent(new ComponentName(ai.PackageName, ai.Name));
  18. StartActivitySafely(startIntent);
  19. return false;
  20. }
  21.  
  22. return base.OnKeyDown(keyCode, e);
  23. }
  24.  
  25. private void StartActivitySafely(Intent intent)
  26. {
  27. intent.AddFlags(ActivityFlags.NewTask);
  28. try
  29. {
  30. StartActivity(intent);
  31. }
  32. catch (ActivityNotFoundException ex)
  33. {
  34. Toast.MakeText(this, "StartActivitySafely()异常:" + ex.Message, ToastLength.Short).Show();
  35. }
  36. catch (SecurityException ex)
  37. {
  38. Toast.MakeText(this, "StartActivitySafely()异常:" + ex.Message, ToastLength.Short).Show();
  39. }
  40. }