首页 > 其他分享 >Xamrin.Forms android端全局异常处理

Xamrin.Forms android端全局异常处理

时间:2022-11-05 22:14:38浏览次数:36  
标签:Environment Xamrin Forms new var using android Android

 

以下为MainActivity中代码

using System;

using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.OS;
using XamrinScanner.Services;
using Android.Content;
using System.Threading.Tasks;
using System.IO;
using Environment = System.Environment;
using System.Diagnostics;

namespace XamrinScanner.Droid
{
    [Activity(Label = "XamrinScanner", Icon = "@mipmap/shoujisaoma", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation | ConfigChanges.UiMode | ConfigChanges.ScreenLayout | ConfigChanges.SmallestScreenSize )]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        public static Context AppContext;
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            //unhander excption event 
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
            TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;

            global::Xamarin.Forms.Forms.SetFlags("FastRenderers_Experimental");
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            AiForms.Dialogs.Dialogs.Init(this); //need to write here

            AppContext = ApplicationContext;

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            App.TodoManager = new TodoManager(new SoapService());
            //App.TodoManager = new TodoManager();
            LoadApplication(new App());
        }
        public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
        {
            Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);

            base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
        }





        //global exception handling
        //link https://peterno.wordpress.com/2015/04/15/unhandled-exception-handling-in-ios-and-android-with-xamarin/

        #region Error handling
        private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
        {
            var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
            LogUnhandledException(newExc);
        }

        private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
        {
            var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
            LogUnhandledException(newExc);
        }

        internal static void LogUnhandledException(Exception exception)
        {
            try
            {
                const string errorFileName = "Fatal.log";
                var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // iOS: Environment.SpecialFolder.Resources
                var errorFilePath = Path.Combine(libraryPath, errorFileName);
                var errorMessage = String.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}",
                DateTime.Now, exception.ToString());
                File.WriteAllText(errorFilePath, errorMessage);

                // Log to Android Device Logging.
                Android.Util.Log.Error("Crash Report", errorMessage);
            }
            catch
            {
                // just suppress any error logging exceptions
            }
        }

        /// <summary>
        // If there is an unhandled exception, the exception information is diplayed 
        // on screen the next time the app is started (only in debug configuration)
        /// </summary>
        [Conditional("DEBUG")]
        private void DisplayCrashReport()
        {
            const string errorFilename = "Fatal.log";
            var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var errorFilePath = Path.Combine(libraryPath, errorFilename);

            if (!File.Exists(errorFilePath))
            {
                return;
            }

            var errorText = File.ReadAllText(errorFilePath);
            new AlertDialog.Builder(this)
                .SetPositiveButton("Clear", (sender, args) =>
                {
                    File.Delete(errorFilePath);
                })
                .SetNegativeButton("Close", (sender, args) =>
                {
                // User pressed Close.
            })
                .SetMessage(errorText)
                .SetTitle("Crash Report")
                .Show();
        }

        #endregion

    }





}

 

标签:Environment,Xamrin,Forms,new,var,using,android,Android
From: https://www.cnblogs.com/chengcanghai/p/16861456.html

相关文章

  • Android通知监听服务之NotificationListenerService使用篇
    前言本篇我们将介绍如何利用NotificationListenerService实现类似智能手表通知同步、微信自动抢红包等功能。实现这些功能的原理其实就是监听系统的通知服务,接下来我们来看......
  • Android 明年将不再支持 32 位应用
    上周,Google正式发布了Android13并率先向Pixel设备推送了系统更新,其他OEM厂商也将跟进这一最新系统,并会在今年晚些时候向他们旗下的设备推送更新。近日,MishaalRahma......
  • Android实现Gestures捕获
    效果图   MainActivitypublicclassMainActivityextendsAppCompatActivityimplementsGestureDetector.OnGestureListener{privateGestureDetector......
  • Android实现UDP通信
    TCP和UDP的不同上次我们讲的是TCP的socket,他们之间的不同在于,tcp要等待客户端的接入,然后获得客户端socket然后进行IO操作,udp直接传送数据即可  图片来源:面试官:说说U......
  • Android 报错:error: too many padding sections on bottom border
     在androidstudio点击png文件修改,把多条黑边改成2条黑边即可 Android报错:error:toomanypaddingsectionsonbottomborder 一、发生错误【我以为我做......
  • 【Android Gradle 插件】自定义 Gradle 插件优化图片 ③ ( 识别 png 图片中的 alpha
    文章目录​​一、识别png图片中的alpha通道信息​​​​1、png图片的文件头信息​​​​2、png图片的数据块​​​​3、png图片的IHDR类型数据块​​​​4、IHDR......
  • Android 嵌套布局简析
    前言嵌套布局是事件分发的衍生内容,理解了嵌套布局的实现方式,Md的很多效果都是毛毛雨了​​原文地址进入​​Uml时序图形嵌套布局实现方式,以及5.0中与嵌套布局有关联的......
  • Android 8.0 + Service开启方式兼容处理
    Android8.0+,对后台服务进行了限制了。如果依然采用之前startService()方式。会导致问题。前后台服务的一些区别:类别区别应用前台服务会在通知一栏显示ONGOING的Notifi......
  • 从android 谈重构
    什麽是重构可以运作的程式跟可以维护的程式之间,还有一道难以言说的鸿沟。一个程式设计之初,是用来解决特定问题。就像在前面章节的学习中,我们也已......
  • Android的BLE广播数据包解析---Android系列, 蓝牙技术(含BLE)
      一、引言理解和分析这个数据包结构(这里面也涉及广播间隔时间的设置,设备广播数据间隔设置长了,会影响设备被发现的效率;设置短时,又响应功耗)。我们所说的BLE设备,其实......