MainActivity.cs 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. 
  2. using System;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Threading.Tasks;
  6. using Android;
  7. using Android.App;
  8. using Android.Content.PM;
  9. using Android.OS;
  10. using Android.Runtime;
  11. using InABox.Mobile.Android;
  12. using Xamarin.Forms;
  13. using Plugin.LocalNotification;
  14. using Android.Content;
  15. using Environment = System.Environment;
  16. using Android.Support.V4.App;
  17. using Xamarin.Essentials;
  18. using System.Linq;
  19. using Android.Annotation;
  20. namespace comal.timesheets.Droid
  21. {
  22. [Activity(
  23. Name = "PRS.Mobile.Droid.MainActivity",
  24. Label = "TimeBench", Icon = "@mipmap/icon",
  25. Theme = "@style/MainTheme", MainLauncher = true,
  26. ConfigurationChanges = ConfigChanges.ScreenSize,
  27. ScreenOrientation = Android.Content.PM.ScreenOrientation.Portrait
  28. )]
  29. [IntentFilter(new[] { Android.Content.Intent.ActionView },
  30. AutoVerify = true,
  31. Categories = new[]
  32. {
  33. Android.Content.Intent.CategoryDefault,
  34. Android.Content.Intent.CategoryBrowsable,
  35. },
  36. DataScheme = "http",
  37. DataPathPrefix = "/open",
  38. DataHost = "www.prsmobile.com")
  39. ]
  40. public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
  41. {
  42. private readonly string[] Permissions =
  43. {
  44. Manifest.Permission.Bluetooth,
  45. Manifest.Permission.BluetoothAdmin,
  46. Manifest.Permission.AccessCoarseLocation,
  47. Manifest.Permission.AccessFineLocation,
  48. Manifest.Permission.BluetoothScan,
  49. Manifest.Permission.BluetoothAdvertise,
  50. Manifest.Permission.BluetoothConnect,
  51. Manifest.Permission.ReadMediaVideo,
  52. Manifest.Permission.ReadMediaAudio,
  53. Manifest.Permission.ReadMediaImages,
  54. };
  55. protected override void OnCreate(Bundle savedInstanceState)
  56. {
  57. CheckPermissions();
  58. DependencyService.Register<Version_Android>();
  59. var data = Intent?.Data?.EncodedAuthority;
  60. if (!string.IsNullOrWhiteSpace(data))
  61. {
  62. try
  63. {
  64. string s = Intent.Data.Path;
  65. s = s.Remove(0, 6);
  66. GlobalVariables.LoadFromLinkString = s;
  67. }
  68. catch { }
  69. }
  70. TabLayoutResource = Resource.Layout.Tabbar;
  71. ToolbarResource = Resource.Layout.Toolbar;
  72. base.OnCreate(savedInstanceState);
  73. AppDomain.CurrentDomain.UnhandledException += CurrentDomainOnUnhandledException;
  74. TaskScheduler.UnobservedTaskException += TaskSchedulerOnUnobservedTaskException;
  75. LocalNotificationCenter.CreateNotificationChannel(new Plugin.LocalNotification.AndroidOption.NotificationChannelRequest
  76. {
  77. Importance = Plugin.LocalNotification.AndroidOption.AndroidImportance.Max,
  78. LockScreenVisibility = Plugin.LocalNotification.AndroidOption.AndroidVisibilityType.Public,
  79. ShowBadge = true,
  80. EnableVibration = true,
  81. Sound = "requiitemadded.mp3"
  82. });
  83. LocalNotificationCenter.NotifyNotificationTapped(Intent);
  84. global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
  85. DisplayCrashReport();
  86. Plugin.CurrentActivity.CrossCurrentActivity.Current.Init(this, savedInstanceState);
  87. Xamarin.Essentials.Platform.Init(this, savedInstanceState);
  88. Syncfusion.XForms.Android.PopupLayout.SfPopupLayoutRenderer.Init();
  89. Xamarin.FormsMaps.Init(this, savedInstanceState);
  90. ZXing.Net.Mobile.Forms.Android.Platform.Init();
  91. XF.Material.Droid.Material.Init(this, savedInstanceState);
  92. LoadApplication(new App());
  93. Window.SetSoftInputMode(Android.Views.SoftInput.AdjustResize);
  94. }
  95. protected override void OnNewIntent(Intent intent)
  96. {
  97. LocalNotificationCenter.NotifyNotificationTapped(intent);
  98. base.OnNewIntent(intent);
  99. }
  100. public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
  101. {
  102. global::ZXing.Net.Mobile.Android.PermissionsHandler.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  103. //at this point in time, xamarin essentials is unable to ask for WRITE_MEDIA_STORAGE from the user, so it never gets granted
  104. //has to be set manually when asked for, in order for API 33 on Android 13 to work
  105. //https://github.com/xamarin/Essentials/issues/2041
  106. if (permissions.ToList().Where(x => x == "WRITE_MEDIA_STORAGE") != null)
  107. {
  108. var grants = new Permission[] { Permission.Granted };
  109. Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grants);
  110. }
  111. else
  112. {
  113. Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  114. }
  115. base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
  116. }
  117. private async void CheckPermissions()
  118. {
  119. bool minimumPermissionsGranted = true;
  120. foreach (string permission in Permissions)
  121. {
  122. if (CheckSelfPermission(permission) != Permission.Granted)
  123. {
  124. minimumPermissionsGranted = false;
  125. }
  126. }
  127. // If any of the minimum permissions aren't granted, we request them from the user
  128. if (!minimumPermissionsGranted)
  129. {
  130. RequestPermissions(Permissions, 0);
  131. }
  132. }
  133. #region Error handling
  134. private static void TaskSchedulerOnUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs unobservedTaskExceptionEventArgs)
  135. {
  136. var newExc = new Exception("TaskSchedulerOnUnobservedTaskException", unobservedTaskExceptionEventArgs.Exception);
  137. LogUnhandledException(newExc);
  138. }
  139. private static void CurrentDomainOnUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
  140. {
  141. var newExc = new Exception("CurrentDomainOnUnhandledException", unhandledExceptionEventArgs.ExceptionObject as Exception);
  142. LogUnhandledException(newExc);
  143. }
  144. internal static void LogUnhandledException(Exception exception)
  145. {
  146. try
  147. {
  148. const string errorFileName = "Fatal.log";
  149. var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // iOS: Environment.SpecialFolder.Resources
  150. var errorFilePath = Path.Combine(libraryPath, errorFileName);
  151. var errorMessage = "";
  152. if (File.Exists(errorFilePath))
  153. {
  154. errorMessage = File.ReadAllText(errorFilePath);
  155. }
  156. errorMessage = errorMessage + System.Environment.NewLine + String.Format("Time: {0}\r\nError: Unhandled Exception\r\n{1}",
  157. DateTime.Now, exception.ToString());
  158. File.WriteAllText(errorFilePath, errorMessage);
  159. // Log to Android Device Logging.
  160. Android.Util.Log.Error("Crash Report", errorMessage);
  161. }
  162. catch
  163. {
  164. // just suppress any error logging exceptions
  165. }
  166. }
  167. /// <summary>
  168. // If there is an unhandled exception, the exception information is diplayed
  169. // on screen the next time the app is started (only in debug configuration)
  170. /// </summary>
  171. [Conditional("DEBUG")]
  172. private void DisplayCrashReport()
  173. {
  174. const string errorFilename = "Fatal.log";
  175. var libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
  176. var errorFilePath = Path.Combine(libraryPath, errorFilename);
  177. if (!File.Exists(errorFilePath))
  178. {
  179. return;
  180. }
  181. var errorText = File.ReadAllText(errorFilePath);
  182. new AlertDialog.Builder(this)
  183. .SetPositiveButton("Clear", (sender, args) =>
  184. {
  185. File.Delete(errorFilePath);
  186. })
  187. .SetNegativeButton("Close", (sender, args) =>
  188. {
  189. // User pressed Close.
  190. })
  191. .SetMessage(errorText)
  192. .SetTitle("Crash Report")
  193. .Show();
  194. }
  195. #endregion
  196. }
  197. }