隐藏

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

发布:2021/10/25 9:17:24作者:管理员 来源:本站 浏览次数:1016

/// <summary>
        /// 重写按键事件
        /// </summary>
        /// <param name="keyCode"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public override bool OnKeyDown([GeneratedEnum] Keycode keyCode, KeyEvent e)
        {
            // 根据某种情形禁用返回键
            if (keyCode == Keycode.Back && disableBack)
            {
                PackageManager pm = PackageManager;
                ResolveInfo homeInfo = pm.ResolveActivity(new Intent(Intent.ActionMain).AddCategory(Intent.CategoryHome), 0);
                ActivityInfo ai = homeInfo.ActivityInfo;
                Intent startIntent = new Intent(Intent.ActionMain);
                startIntent.AddCategory(Intent.CategoryLauncher);
                startIntent.SetComponent(new ComponentName(ai.PackageName, ai.Name));
                StartActivitySafely(startIntent);
                return false;
            }

            return base.OnKeyDown(keyCode, e);
        }

        private void StartActivitySafely(Intent intent)
        {
            intent.AddFlags(ActivityFlags.NewTask);
            try
            {
                StartActivity(intent);
            }
            catch (ActivityNotFoundException ex)
            {
                Toast.MakeText(this, "StartActivitySafely()异常:" + ex.Message, ToastLength.Short).Show();
            }
            catch (SecurityException ex)
            {
                Toast.MakeText(this, "StartActivitySafely()异常:" + ex.Message, ToastLength.Short).Show();
            }
        }