-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.xaml.cs
579 lines (537 loc) · 23.6 KB
/
App.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
using Microsoft.Toolkit.Uwp.Notifications;
using Microsoft.Toolkit.Uwp.Helpers;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.ApplicationModel.Background;
using Windows.ApplicationModel.Core;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.System;
using Windows.UI.Notifications;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;
using Live_Music.Helpers;
using Live_Music.Services;
using Windows.UI.Core.Preview;
using Windows.UI.Core;
using System.Text;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Windows.Devices.Portable;
using System.Text.Json;
using System.Runtime.Serialization.Formatters.Binary;
namespace Live_Music
{
/// <summary>
/// 提供特定于应用程序的行为,以补充默认的应用程序类。
/// </summary>
sealed partial class App : Application
{
/// <summary>
/// 初始化单一实例应用程序对象。这是执行的创作代码的第一行,
/// 已执行,逻辑上等同于 main() 或 WinMain()。
/// </summary>
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
this.UnhandledException += AppExceptionHandler; //应用程序层级的异常处理
//进入或退出后台时进行管理
this.EnteredBackground += AppEnteredBackground;
this.LeavingBackground += AppLeavingBackground;
MemoryManager.AppMemoryUsageLimitChanging += AppMemoryUsageLimitChanging; //内存限制改变时的操作
MemoryManager.AppMemoryUsageIncreased += AppMemoryUsageIncreased; //内存增加到上限值时的操作
FocusVisualKind = FocusVisualKind.Reveal;
string ThemeSettings = (string)localSettings.Values["ThemeSetting"];
switch (ThemeSettings)
{
case "Light":
Current.RequestedTheme = ApplicationTheme.Light;
break;
case "Dark":
Current.RequestedTheme = ApplicationTheme.Dark;
break;
case "Default":
break;
case null:
break;
}
#if DEBUG
Debug.WriteLine("[Info]现在的设置列表:");
foreach (var item in localSettings.Values)
{
Debug.WriteLine(item.ToString());
}
#endif
}
private delegate void UnhandledExceptionHappened();
/// <summary>
/// 应用程序设置的实例
/// </summary>
public static Settings settings = new Settings();
/// <summary>
/// 音乐信息的实例
/// </summary>
public static MusicInfomation musicInfomation = new MusicInfomation();
/// <summary>
/// 音乐服务的实例
/// </summary>
public static MusicService musicService = new MusicService();
/// <summary>
/// 声音图标状态的实例
/// </summary>
public static VolumeGlyphState volumeGlyphState = new VolumeGlyphState();
/// <summary>
/// 应用程序运行过程中的信息的实例
/// </summary>
public static AppInfomation appInfomation = new AppInfomation();
/// <summary>
/// 音乐历史记录的实例
/// </summary>
public static MusicHistoryHelper musicHistoryHelper = new MusicHistoryHelper();
/// <summary>
/// 在用户代码中未处理的异常的出现数量
/// </summary>
private int UnhandledExceptionCount = 0;
/// <summary>
/// 异常的详细信息
/// </summary>
public static string[] UnhandledExceptionMessage = { "FullName", "Message", "StackTrace" };
/// <summary>
/// 此值指示未处理的异常是否出现了三次
/// </summary>
public static bool IsExceptionHappenedOverThree = false;
/// <summary>
/// 此值指示应用是否在后台模式
/// </summary>
private bool IsInBackgroundMode;
private ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
/// <summary>
/// 未在用户代码中处理的异常的异常处理程序
/// </summary>
/// <param name="sender">出现异常的源</param>
/// <param name="e">有关异常的详细信息</param>
private void AppExceptionHandler(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
e.Handled = true;
appInfomation.IsInfoBarButtonShow = Visibility.Visible;
appInfomation.InfoBarTitle = "应用程序出现了一个异常";
appInfomation.InfoBarMessage = "您可以向我们报告,也可以忽略该错误。";
appInfomation.InfoBarSeverity = Microsoft.UI.Xaml.Controls.InfoBarSeverity.Error;
appInfomation.InfoBarButtonClick = (object sender1, RoutedEventArgs e1) => OpenExceptionDialog(e);
appInfomation.IsInfoBarOpen = true;
}
/// <summary>
/// 打开异常详细信息的对话框
/// </summary>
/// <param name="e"></param>
/// <returns></returns>
private async void OpenExceptionDialog(Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
UnhandledExceptionCount++;
UnhandledExceptionMessage[0] = e.Exception.GetType().FullName;
UnhandledExceptionMessage[1] = e.Exception.ToString();
var stackFrames = new StackTrace(e.Exception).GetFrames() ?? new StackFrame[0];
var frames = stackFrames.Select(x => x.GetMethod()).Select(m =>
$"{m.DeclaringType?.FullName ?? "null"}.{m.Name}({string.Join(", ", m.GetParameters().Select(p => $"{p.ParameterType.Name} {p.Name}"))})");
StringBuilder stringBuilder = new StringBuilder();
foreach (string text in frames.ToList())
{
stringBuilder.Append(text);
}
UnhandledExceptionMessage[2] = string.IsNullOrWhiteSpace(stringBuilder.ToString()) == true ? "null" : stringBuilder.ToString();
ExceptionDetails.ExceptionDetailsDialog exceptionDetailsDialog = new ExceptionDetails.ExceptionDetailsDialog();
TextBlock textBlock = new TextBlock();
if (UnhandledExceptionCount > 3)
{
Debug.WriteLine("\n[Exception]出现了未在用户代码中进行处理的异常,且此异常出现了3次以上!");
Debug.WriteLine($"[Exception]这种情况出现了{UnhandledExceptionCount}次。");
Debug.WriteLine($"[Exception]更多信息:\n{e.Message}");
exceptionDetailsDialog.Title = $"应用程序出现了一个异常";
exceptionDetailsDialog.Content = textBlock.Text = $"(!)异常出现了三次以上,强烈建议向我们报告这个问题\n\n异常名称:{e.Exception.GetType().FullName}\n详细信息:{e.Message}";
IsExceptionHappenedOverThree = true;
try
{
await exceptionDetailsDialog.ShowAsync();
}
catch (Exception)
{
UnhandledExceptionCount = 4;
}
}
else
{
Debug.WriteLine("\n[Exception]出现了未在用户代码中进行处理的异常!");
Debug.WriteLine($"[Exception]这种情况出现了{UnhandledExceptionCount}次。");
Debug.WriteLine($"[Exception]更多信息:\n{e.Message}");
exceptionDetailsDialog.Title = $"应用程序出现了一个异常";
exceptionDetailsDialog.Content = textBlock.Text = $"异常名称:{e.Exception.GetType().FullName}\n详细信息:{e.Message}";
try
{
await exceptionDetailsDialog.ShowAsync();
}
catch (Exception)
{
UnhandledExceptionCount = 1;
}
}
}
/// <summary>
/// 当应用进入后台时的操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppEnteredBackground(object sender, EnteredBackgroundEventArgs e)
{
IsInBackgroundMode = true;
Debug.WriteLine("[StateChanged]已进入后台");
}
/// <summary>
/// 当应用离开后台时的操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppLeavingBackground(object sender, LeavingBackgroundEventArgs e)
{
IsInBackgroundMode = false;
if (Window.Current.Content == null)
{
CreateRootFrame(ApplicationExecutionState.Running, string.Empty);
}
Debug.WriteLine("[StateChanged]已离开后台");
}
/// <summary>
/// 当应用的内存限制量改变时的操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppMemoryUsageLimitChanging(object sender, AppMemoryUsageLimitChangingEventArgs e)
{
Debug.WriteLine("[MemoryUsage]内存限制量发生了改变");
if (MemoryManager.AppMemoryUsage >= e.NewLimit)
{
ReduceMemoryUsage();
}
}
/// <summary>
/// 当应用的内存使用量增加到上限值时的操作
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void AppMemoryUsageIncreased(object sender, object e)
{
var level = MemoryManager.AppMemoryUsageLevel;
if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
{
Debug.WriteLine("[MemoryUsage]警告:内存使用量到达上限");
ReduceMemoryUsage();
}
}
/// <summary>
/// 减少应用的内存使用量时使用的操作
/// </summary>
/// <param name="limit"></param>
public void ReduceMemoryUsage()
{
Debug.WriteLine("[MemoryUsage]正在尝试减少应用内存使用量");
if (IsInBackgroundMode == true && Window.Current.Content != null)
{
Debug.WriteLine("[MemoryUsage]正在卸载主页面内容");
Window.Current.Content = null;
Debug.WriteLine("[MemoryUsage]正在清理音乐及其信息服务的资源...");
musicService.Dispose();
musicInfomation.ResetAllMusicProperties();
Debug.WriteLine("[MemoryUsage]完成。");
}
Debug.WriteLine("[MemoryUsage]正强制启动垃圾回收器");
GC.Collect();
}
/// <summary>
/// 当应用离开后台时发现主界面内容为空时的操作
/// </summary>
/// <param name="previousExecutionState"></param>
/// <param name="arguments"></param>
void CreateRootFrame(ApplicationExecutionState previousExecutionState, string arguments)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.Language = Windows.Globalization.ApplicationLanguages.Languages[0];
rootFrame.NavigationFailed += OnNavigationFailed;
//重新实例化音乐及其信息服务
musicInfomation = new MusicInfomation();
musicService = new MusicService();
if (previousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: 从之前挂起的应用程序加载状态
musicService.mediaPlayer.Volume = settings.MusicVolume;
}
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), arguments);
}
NotifyUserContectLost();
}
/// <summary>
/// 通知用户内容可能已经丢失,这是通过Toast通知实现的
/// </summary>
private void NotifyUserContectLost()
{
var toastContent = new ToastContent()
{
Visual = new ToastVisual()
{
BindingGeneric = new ToastBindingGeneric()
{
Children =
{
new AdaptiveText()
{
Text = "非常抱歉"
},
new AdaptiveText()
{
Text = "因为内存限制,应用的某些内容可能已经丢失"
}
}
}
}
};
// Create the toast notification
var toastNotif = new ToastNotification(toastContent.GetXml());
// And send the notification
ToastNotificationManager.CreateToastNotifier().Show(toastNotif);
}
private void OnBackRequested(object sender, Windows.UI.Core.BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
return;
}
//当可以返回到上一个页面,且返回事件尚未被处理时发生
if (rootFrame.CanGoBack && e.Handled == false)
{
e.Handled = true;
rootFrame.GoBack();
if (SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility == AppViewBackButtonVisibility.Visible)
{
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility = AppViewBackButtonVisibility.Collapsed;
}
}
}
/// <summary>
/// 在应用程序由最终用户正常启动时进行调用。
/// 将在启动应用程序以打开特定文件等情况下使用。
/// </summary>
/// <param name="e">有关启动请求和过程的详细信息。</param>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
Window.Current.Content = rootFrame;
//当系统收到回退请求(BackRequested)的时候,就会调用方法OnBackRequested来处理该事件
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
// 隐藏标题栏
var coreTitleBar = CoreApplication.GetCurrentView().TitleBar;
coreTitleBar.ExtendViewIntoTitleBar = true;
//标题栏按钮颜色
var titleBar = ApplicationView.GetForCurrentView().TitleBar;
titleBar.ButtonBackgroundColor = Windows.UI.Colors.Transparent;
//if (File.Exists($"{ApplicationData.Current.LocalFolder.Path}\\MusicHistory.bin"))
//{
// StorageFile binFile = await ApplicationData.Current.LocalFolder.GetFileAsync("MusicHistory.bin");
// Stream stream = await binFile.OpenStreamForReadAsync();
// BinaryFormatter binaryFormatter = new BinaryFormatter();
// musicHistoryHelper.MusicHistoryItemsProperty = binaryFormatter.Deserialize(stream) as Dictionary<string, MusicHistoryTemplate>;
//}
#region 暂时不用的代码
//var WhiteBlack = (Color)Application.Current.Resources["WhiteBlack"];
//titleBar.ButtonForegroundColor = WhiteBlack;
#endregion
// 不要在窗口已包含内容时重复应用程序初始化,
// 只需确保窗口处于活动状态
if (rootFrame == null)
{
// 创建要充当导航上下文的框架,并导航到第一页
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: 从之前挂起的应用程序加载状态
Debug.WriteLine("[Resume]上次的状态:挂起后被关闭");
Debug.WriteLine("[Resume]已自动恢复以下信息:播放器音量");
}
// 将框架放在当前窗口中
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
// 当导航堆栈尚未还原时,导航到第一页,
// 并通过将所需信息作为导航参数传入来配置参数
if (SystemInformation.IsFirstRun == true)
{
rootFrame.Navigate(typeof(FirstStart), null, new SuppressNavigationTransitionInfo());
settings.MusicVolume = 1d;
}
else
{
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
}
// 确保当前窗口处于活动状态
Window.Current.Activate();
}
}
/// <summary>
/// 导航到特定页失败时调用
/// </summary>
///<param name="sender">导航失败的框架</param>
///<param name="e">有关导航失败的详细信息</param>
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("加载页面失败! " + e.SourcePageType.FullName);
}
/// <summary>
/// 在将要挂起应用程序的执行时调用。 保存应用程序状态,
/// 无需知道应用程序是要被终止
/// 还是在内存内容原封未动时恢复
/// </summary>
/// <param name="sender">挂起的请求的源。</param>
/// <param name="e">有关挂起请求的详细信息。</param>
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: 保存应用程序状态并停止任何后台活动
Debug.WriteLine("[Suspending]将要进入挂起态");
settings.MusicVolume = musicService.mediaPlayer.Volume; //保存现在的音量
Debug.WriteLine("[Suspending]已保存现在的音量");
//Debug.WriteLine("[Suspending]正在保存当前的播放历史记录");
//StorageFile binFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("MusicHistory.bin", CreationCollisionOption.ReplaceExisting);
//BinaryFormatter binaryFormatter = new BinaryFormatter();
//Stream stream = await binFile.OpenStreamForWriteAsync();
//binaryFormatter.Serialize(stream, musicHistoryHelper.MusicHistoryItemsProperty);
//stream.Dispose();
//Debug.WriteLine("[Suspending]保存当前的播放历史记录完成");
Debug.WriteLine("[Suspending]进入挂起态");
deferral.Complete();
}
/// <summary>
/// 当应用打开某个音乐文件时调用的方法
/// </summary>
/// <param name="args"></param>
protected override void OnFileActivated(FileActivatedEventArgs args)
{
if (args.Verb == "playMusic")
{
IReadOnlyList<StorageFile> fileList = (from StorageFile file in args.Files where IsMusicFile(file) select file).AsParallel().ToList();
if (!(Window.Current.Content is Frame frame))
{
frame = new Frame();
Window.Current.Content = frame;
}
frame.Navigate(typeof(MainPage), fileList);
}
else
{
List<StorageFile> storageFiles = new List<StorageFile>();
foreach (var item in args.Files)
{
storageFiles.Add((StorageFile)item);
}
IReadOnlyList<StorageFile> file = storageFiles;
if (!(Window.Current.Content is Frame frame))
{
frame = new Frame();
Window.Current.Content = frame;
frame.Navigate(typeof(MainPage), file);
}
}
Window.Current.Activate();
base.OnFileActivated(args);
bool IsMusicFile(StorageFile file)
{
switch (file.ContentType)
{
case "audio/mpeg":
return true;
case "audio/x-wav":
return true;
default:
return false;
}
}
}
protected override async void OnActivated(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Device)
{
Frame rootFrame = null;
if (Window.Current.Content == null)
{
rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage));
Window.Current.Content = rootFrame;
}
else
{
rootFrame = Window.Current.Content as Frame;
}
bool storageDeviceAPIPresent = Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Devices.Portable.StorageDevice");
if (storageDeviceAPIPresent)
{
var deviceArgs = args as DeviceActivatedEventArgs;
#if DEBUG
Debug.WriteLine("[Info]启动了自动播放");
Debug.WriteLine($"[Info]激活类型{deviceArgs.Kind}");
Debug.WriteLine($"[Info]设备标识符{deviceArgs.DeviceInformationId}");
#endif
IReadOnlyList<StorageFile> fileList = (from StorageFile file in await StorageDevice.FromId(deviceArgs.DeviceInformationId).GetItemsAsync() where IsMusicFile(file) select file).AsParallel().ToList();
if (!(Window.Current.Content is Frame frame))
{
frame = new Frame();
Window.Current.Content = frame;
}
frame.Navigate(typeof(MainPage), fileList);
bool IsMusicFile(StorageFile file)
{
switch (file.ContentType)
{
case "audio/mpeg":
return true;
case "audio/x-wav":
return true;
default:
return false;
}
}
}
else
{
// Do nothing
}
}
base.OnActivated(args);
}
}
}