-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathDownloaderService.cs
1307 lines (1118 loc) · 44.7 KB
/
DownloaderService.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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="DownloaderService.cs" company="Matthew Leibowitz">
// Copyright (c) Matthew Leibowitz
// This code is licensed under the Apache 2.0 License
// http://www.apache.org/licenses/LICENSE-2.0.html
// </copyright>
// <summary>
// The downloader service.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ExpansionDownloader.Service
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Net;
using Android.Net.Wifi;
using Android.OS;
using Android.Runtime;
using Android.Telephony;
using Android.Util;
using ExpansionDownloader.Database;
using Java.Util;
using LicenseVerificationLibrary.Policy;
using Debug = System.Diagnostics.Debug;
/// <summary>
/// The downloader service.
/// </summary>
public abstract partial class DownloaderService : CustomIntentService, IDownloaderService
{
#region Constants
public const string Tag = "DownloaderService";
/// <summary>
/// The buffer size used to stream the data.
/// </summary>
public const int BufferSize = 4096;
/// <summary>
/// The default user agent used for downloads.
/// </summary>
public const string DefaultUserAgent = "Android.LVLDM";
/// <summary>
/// The maximum number of redirects. (can't be more than 7)
/// </summary>
public const int MaxRedirects = 5;
/// <summary>
/// The number of times that the download manager will retry its network
/// operations when no progress is happening before it gives up.
/// </summary>
public const int MaximumRetries = 5;
/// <summary>
/// The minimum amount of progress that has to be done before the
/// progress bar gets updated.
/// </summary>
public const int MinimumProgressStep = 4096;
/// <summary>
/// The minimum amount of time that has to elapse before the progress
/// bar gets updated, in milliseconds.
/// </summary>
public const long MinimumProgressTime = 1000;
/// <summary>
/// The minimum amount of time that the download manager accepts for
/// a Retry-After response header with a parameter in delta-seconds.
/// </summary>
public const int MinimumRetryAfter = 30;
/// <summary>
/// The time between a failure and the first retry after an IOException.
/// Each subsequent retry grows exponentially, doubling each time.
/// The time is in seconds.
/// </summary>
public const int RetryFirstDelay = 30;
/// <summary>
/// The wake duration to check to see if a download is possible. (seconds)
/// </summary>
public const int WatchdogWakeTimer = 60;
/// <summary>
/// The wake duration to check to see if the process was killed. (seconds)
/// </summary>
private const int ActiveThreadWatchdog = 5;
/// <summary>
/// When a number has to be appended to the filename, this string is
/// used to separate the base filename from the sequence number.
/// </summary>
private const string FilenameSequenceSeparator = "-";
/// <summary>
/// The maximum number of rows in the database (FIFO).
/// </summary>
private const int MaximumDownloads = 1000;
/// <summary>
/// Service thread status
/// </summary>
private const float SmoothingFactor = 0.005f;
/// <summary>
/// The temporary file extension.
/// </summary>
private const string TemporaryFileExtension = ".tmp";
#endregion
#region Static Fields
/// <summary>
/// The maximum amount of time that the download manager accepts for a
/// Retry-After response header with a parameter in delta-seconds.
/// </summary>
public static readonly int MaxRetryAfter = (int)TimeSpan.FromDays(1).TotalSeconds;
/// <summary>
/// Service thread status
/// </summary>
private static volatile bool isRunning;
#endregion
#region Fields
/// <summary>
/// The locker.
/// </summary>
private readonly object locker = new object();
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private readonly IDownloaderServiceConnection serviceConnection;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private readonly Messenger serviceMessenger;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private PendingIntent alarmIntent;
/// <summary>
/// Used for calculating time remaining and speed
/// </summary>
private float averageDownloadSpeed;
/// <summary>
/// Used for calculating time remaining and speed
/// </summary>
private long bytesAtSample;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private Messenger clientMessenger;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private BroadcastReceiver connectionReceiver;
/// <summary>
/// Bindings to important services
/// </summary>
private ConnectivityManager connectivityManager;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private DownloadNotification downloadNotification;
/// <summary>
/// Byte counts
/// </summary>
private int fileCount;
/// <summary>
/// Used for calculating time remaining and speed
/// </summary>
private long millisecondsAtSample;
/// <summary>
/// The current network state.
/// </summary>
private NetworkState networkState;
/// <summary>
/// Our binding to the network state broadcasts
/// </summary>
private PendingIntent pPendingIntent;
/// <summary>
/// Package we are downloading for (defaults to package of application)
/// </summary>
private PackageInfo packageInfo;
/// <summary>
/// Network state.
/// </summary>
private bool stateChanged;
/// <summary>
/// The status.
/// </summary>
private ExpansionDownloadStatus status;
/// <summary>
/// Bindings to important services
/// </summary>
private WifiManager wifiManager;
#endregion
#region Constructors and Destructors
/// <summary>
/// Initializes a new instance of the <see cref="DownloaderService"/> class.
/// </summary>
protected DownloaderService()
: base("LVLDownloadService")
{
Log.Debug(Tag,"LVLDL DownloaderService()");
this.serviceConnection = ServiceMarshaller.CreateStub(this);
this.serviceMessenger = this.serviceConnection.GetMessenger();
this.Control = DownloadsDatabase.DownloadStatus == ExpansionDownloadStatus.PausedByApp
? ControlAction.Paused
: ControlAction.Run;
}
#endregion
#region Enums
/// <summary>
/// The network state.
/// </summary>
[Flags]
protected enum NetworkState
{
/// <summary>
/// The disconnected.
/// </summary>
Disconnected = 0,
/// <summary>
/// The connected.
/// </summary>
Connected = 1,
/// <summary>
/// The roaming.
/// </summary>
Roaming = 2,
/// <summary>
/// The is 3 g.
/// </summary>
Is3G = 4,
/// <summary>
/// The is 4 g.
/// </summary>
Is4G = 8,
/// <summary>
/// The is cellular.
/// </summary>
IsCellular = 16,
/// <summary>
/// The is fail over.
/// </summary>
IsFailOver = 32
}
#endregion
#region Public Properties
/// <summary>
/// Gets the number of bytes downloaded so far
/// </summary>
public long BytesSoFar { get; private set; }
/// <summary>
/// Gets the cntrol action.
/// </summary>
public ControlAction Control { get; private set; }
/// <summary>
/// Gets or sets the download state
/// </summary>
public ExpansionDownloadStatus Status
{
get
{
return this.status;
}
set
{
this.status = value;
DownloadsDatabase.UpdateMetadata(DownloadsDatabase.VersionCode, this.status);
}
}
/// <summary>
/// Gets the total length of the downloads.
/// </summary>
public long TotalLength { get; private set; }
#endregion
#region Properties
/// <summary>
/// Gets AlarmReceiverClassName.
/// </summary>
protected abstract string AlarmReceiverClassName { get; }
/// <summary>
/// Gets PublicKey.
/// </summary>
protected abstract string PublicKey { get; }
/// <summary>
/// Gets Salt.
/// </summary>
protected abstract byte[] Salt { get; }
/// <summary>
/// Gets or sets a value indicating whether the service is running.
/// Note: Only use this internally.
/// </summary>
private bool IsServiceRunning
{
get
{
lock (this.locker)
{
return isRunning;
}
}
set
{
lock (this.locker)
{
isRunning = value;
}
}
}
#endregion
#region Public Methods and Operators
/// <summary>
/// This version assumes that the intent contains the pending intent as
/// a parameter. This is used for responding to alarms.
/// The pending intent must be in an extra with the key
/// <see cref="DownloaderService#PendingIntent"/>.
/// </summary>
/// <param name="context">
/// Your application Context.
/// </param>
/// <param name="intent">
/// An Intent to start the Activity in your application that
/// shows the download progress and which will also start the
/// application when downloadcompletes.
/// </param>
/// <param name="serviceType">
/// The type of the service to start.
/// </param>
/// <returns>
/// Whether the service was started and the reason for starting the
/// service.
/// Either <see cref="DownloadServiceRequirement.NoDownloadRequired"/>,
/// <see cref="DownloadServiceRequirement.LvlCheckRequired"/>, or
/// <see cref="DownloadServiceRequirement.DownloadRequired"/>
/// </returns>
public static DownloadServiceRequirement StartDownloadServiceIfRequired(
Context context, Intent intent, Type serviceType)
{
var pendingIntent = (PendingIntent)intent.GetParcelableExtra(DownloaderServiceExtras.PendingIntent);
return StartDownloadServiceIfRequired(context, pendingIntent, serviceType);
}
/// <summary>
/// Starts the download if necessary.
/// </summary>
/// <remarks>
/// This function starts a flow that
/// does many things:
/// 1) Checks to see if the APK version has been checked and the
/// metadata database updated
/// 2) If the APK version does not match, checks the new LVL status
/// to see if a new download is required
/// 3) If the APK version does match, then checks to see if the
/// download(s) have been completed
/// 4) If the downloads have been completed, returns
/// <see cref="DownloadServiceRequirement.NoDownloadRequired"/>
/// The idea is that this can be called during the startup of an
/// application to quickly ascertain if the application needs to wait
/// to hear about any updated APK expansion files.
/// This does mean that the application MUST be run with a network
/// connection for the first time, even if Market delivers all of the
/// files.
/// </remarks>
/// <param name="context">
/// Your application Context.
/// </param>
/// <param name="pendingIntent">
/// A PendingIntent to start the Activity in your application that
/// shows the download progress and which will also start the
/// application when downloadcompletes.
/// </param>
/// <param name="serviceType">
/// The class of your <see cref="DownloaderService"/> implementation.
/// </param>
/// <returns>
/// Whether the service was started and the reason for starting the
/// service.
/// Either <see cref="DownloadServiceRequirement.NoDownloadRequired"/>,
/// <see cref="DownloadServiceRequirement.LvlCheckRequired"/>, or
/// <see cref="DownloadServiceRequirement.DownloadRequired"/>
/// </returns>
public static DownloadServiceRequirement StartDownloadServiceIfRequired(
Context context, PendingIntent pendingIntent, Type serviceType)
{
// first: do we need to do an LVL update?
// we begin by getting our APK version from the package manager
PackageInfo pi = context.PackageManager.GetPackageInfo(context.PackageName, 0);
var status = DownloadServiceRequirement.NoDownloadRequired;
// we need to update the LVL check and get a successful status to proceed
if (IsLvlCheckRequired(pi))
{
status = DownloadServiceRequirement.LvlCheckRequired;
}
// we don't have to update LVL. Do we still have a download to start?
if (DownloadsDatabase.DownloadStatus == ExpansionDownloadStatus.None)
{
List<DownloadInfo> infos = DownloadsDatabase.GetDownloads();
IEnumerable<DownloadInfo> nonExisting =
infos.Where(i => !Helpers.DoesFileExist(context, i.FileName, i.TotalBytes, true));
if (nonExisting.Any())
{
status = DownloadServiceRequirement.DownloadRequired;
DownloadsDatabase.DownloadStatus = ExpansionDownloadStatus.Unknown;
}
}
else
{
status = DownloadServiceRequirement.DownloadRequired;
}
switch (status)
{
case DownloadServiceRequirement.DownloadRequired:
case DownloadServiceRequirement.LvlCheckRequired:
var fileIntent = new Intent(context.ApplicationContext, serviceType);
fileIntent.PutExtra(DownloaderServiceExtras.PendingIntent, pendingIntent);
context.StartService(fileIntent);
break;
}
return status;
}
/// <summary>
/// Creates a filename (where the file should be saved) from info about a download.
/// </summary>
/// <param name="filename">
/// The filename.
/// </param>
/// <param name="filesize">
/// The filesize.
/// </param>
/// <returns>
/// The generate save file.
/// </returns>
public string GenerateSaveFile(string filename, long filesize)
{
string path = this.GenerateTempSaveFileName(filename);
if (!Helpers.IsExternalMediaMounted)
{
Log.Debug(Tag,"External media not mounted: {0}", path);
throw new GenerateSaveFileError(ExpansionDownloadStatus.DeviceNotFoundError, "external media is not yet mounted");
}
if (File.Exists(path))
{
Log.Debug(Tag,"File already exists: {0}", path);
throw new GenerateSaveFileError(
ExpansionDownloadStatus.FileAlreadyExists, "requested destination file already exists");
}
if (Helpers.GetAvailableBytes(Helpers.GetFileSystemRoot(path)) < filesize)
{
throw new GenerateSaveFileError(
ExpansionDownloadStatus.InsufficientSpaceError, "insufficient space on external storage");
}
return path;
}
/// <summary>
/// Returns the filename (where the file should be saved) from info about a download
/// </summary>
/// <param name="fileName">
/// The file Name.
/// </param>
/// <returns>
/// The generate temp save file name.
/// </returns>
public string GenerateTempSaveFileName(string fileName)
{
return string.Format(
"{0}{1}{2}{3}",
Helpers.GetSaveFilePath(this),
Path.DirectorySeparatorChar,
fileName,
TemporaryFileExtension);
}
/// <summary>
/// a non-localized string appropriate for logging corresponding to one of the NETWORK_* constants.
/// </summary>
/// <param name="networkError">
/// The network Error.
/// </param>
/// <returns>
/// The get log message for network error.
/// </returns>
public string GetLogMessageForNetworkError(NetworkDisabledState networkError)
{
switch (networkError)
{
case NetworkDisabledState.RecommendedUnusableDueToSize:
return "download size exceeds recommended limit for mobile network";
case NetworkDisabledState.UnusableDueToSize:
return "download size exceeds limit for mobile network";
case NetworkDisabledState.NoConnection:
return "no network connection available";
case NetworkDisabledState.CannotUseRoaming:
return "download cannot use the current network connection because it is roaming";
case NetworkDisabledState.TypeDisallowedByRequestor:
return "download was requested to not use the current network type";
default:
return "unknown error with network connectivity";
}
}
/// <summary>
/// Calculating a moving average for the speed so we don't get jumpy calculations for time etc.
/// </summary>
/// <param name="totalBytesSoFar">
/// The total Bytes So Far.
/// </param>
public void NotifyUpdateBytes(long totalBytesSoFar)
{
long timeRemaining;
long currentTime = SystemClock.UptimeMillis();
if (0 != this.millisecondsAtSample)
{
// we have a sample.
long timePassed = currentTime - this.millisecondsAtSample;
long bytesInSample = totalBytesSoFar - this.bytesAtSample;
float currentSpeedSample = bytesInSample / (float)timePassed;
if (Math.Abs(0 - this.averageDownloadSpeed) > SmoothingFactor)
{
float smoothSpeed = SmoothingFactor * currentSpeedSample;
float averageSpeed = (1 - SmoothingFactor) * this.averageDownloadSpeed;
this.averageDownloadSpeed = smoothSpeed + averageSpeed;
}
else
{
this.averageDownloadSpeed = currentSpeedSample;
}
timeRemaining = (long)((this.TotalLength - totalBytesSoFar) / this.averageDownloadSpeed);
}
else
{
timeRemaining = -1;
}
this.millisecondsAtSample = currentTime;
this.bytesAtSample = totalBytesSoFar;
this.downloadNotification.OnDownloadProgress(
new DownloadProgressInfo(this.TotalLength, totalBytesSoFar, timeRemaining, this.averageDownloadSpeed));
}
/// <summary>
/// The on bind.
/// </summary>
/// <param name="intent">
/// The intent.
/// </param>
/// <returns>
/// the binder
/// </returns>
public override IBinder OnBind(Intent intent)
{
return this.serviceMessenger.Binder;
}
/// <summary>
/// The on client updated.
/// </summary>
/// <param name="messenger">
/// The client messenger.
/// </param>
public void OnClientUpdated(Messenger messenger)
{
this.clientMessenger = messenger;
this.downloadNotification.SetMessenger(this.clientMessenger);
}
/// <summary>
/// The on create.
/// </summary>
public override void OnCreate()
{
base.OnCreate();
try
{
this.packageInfo = this.PackageManager.GetPackageInfo(this.PackageName, 0);
string applicationLabel = this.PackageManager.GetApplicationLabel(this.ApplicationInfo);
this.downloadNotification = new DownloadNotification(this, applicationLabel);
}
catch (PackageManager.NameNotFoundException e)
{
Log.Error(Tag, e, "Oh oh!");
}
}
/// <summary>
/// The on destroy.
/// </summary>
public override void OnDestroy()
{
if (this.connectionReceiver != null)
{
this.UnregisterReceiver(this.connectionReceiver);
this.connectionReceiver = null;
}
this.serviceConnection.Disconnect(this);
base.OnDestroy();
}
/// <summary>
/// The request abort download.
/// </summary>
public void RequestAbortDownload()
{
this.Control = ControlAction.Paused;
this.Status = ExpansionDownloadStatus.Canceled;
}
/// <summary>
/// The request continue download.
/// </summary>
public void RequestContinueDownload()
{
Log.Debug(Tag,"RequestContinueDownload");
if (this.Control == ControlAction.Paused)
{
this.Control = ControlAction.Run;
}
var fileIntent = new Intent(this, this.GetType());
fileIntent.PutExtra(DownloaderServiceExtras.PendingIntent, this.pPendingIntent);
this.StartService(fileIntent);
}
/// <summary>
/// The request download status.
/// </summary>
public void RequestDownloadStatus()
{
this.downloadNotification.ResendState();
}
/// <summary>
/// The request pause download.
/// </summary>
public void RequestPauseDownload()
{
this.Control = ControlAction.Paused;
this.Status = ExpansionDownloadStatus.PausedByApp;
}
/// <summary>
/// The set download flags.
/// </summary>
/// <param name="flags">
/// The flags.
/// </param>
public void SetDownloadFlags(ServiceFlags flags)
{
DownloadsDatabase.Flags = flags;
}
#endregion
#region Methods
/// <summary>
/// The get network availability state.
/// </summary>
/// <returns>
/// The ExpansionDownloader.Service.NetworkDisabledState.
/// </returns>
internal NetworkDisabledState GetNetworkAvailabilityState()
{
if (!this.networkState.HasFlag(NetworkState.Connected))
{
return NetworkDisabledState.NoConnection;
}
if (!this.networkState.HasFlag(NetworkState.IsCellular))
{
return NetworkDisabledState.Ok;
}
if (this.networkState.HasFlag(NetworkState.Roaming))
{
return NetworkDisabledState.CannotUseRoaming;
}
if (!DownloadsDatabase.Flags.HasFlag(ServiceFlags.FlagsDownloadOverCellular))
{
return NetworkDisabledState.TypeDisallowedByRequestor;
}
return NetworkDisabledState.Ok;
}
/// <summary>
/// Updates the network type based upon the info returned from the
/// connectivity manager.
/// </summary>
/// <param name="info">
/// </param>
/// <returns>
/// The ExpansionDownloader.Service.DownloaderService+NetworkState.
/// </returns>
private NetworkState GetNetworkState(NetworkInfo info)
{
var state = NetworkState.Disconnected;
switch (info.Type)
{
case ConnectivityType.Wifi:
#if __ANDROID_13__
case ConnectivityType.Ethernet:
case ConnectivityType.Bluetooth:
#endif
break;
case ConnectivityType.Wimax:
state = NetworkState.Is3G | NetworkState.Is4G | NetworkState.IsCellular;
break;
case ConnectivityType.Mobile:
state = NetworkState.IsCellular;
switch ((NetworkType)info.Subtype)
{
case NetworkType.OneXrtt:
case NetworkType.Cdma:
case NetworkType.Edge:
case NetworkType.Gprs:
case NetworkType.Iden:
break;
case NetworkType.Hsdpa:
case NetworkType.Hsupa:
case NetworkType.Hspa:
case NetworkType.Evdo0:
case NetworkType.EvdoA:
case NetworkType.Umts:
state |= NetworkState.Is3G;
break;
#if __ANDROID_11__
case NetworkType.Lte:
case NetworkType.Ehrpd:
state |= NetworkState.Is3G | NetworkState.Is4G;
break;
#endif
#if __ANDROID_13__
case NetworkType.Hspap:
state |= NetworkState.Is3G | NetworkState.Is4G;
break;
#endif
}
break;
}
return state;
}
/// <summary>
/// This is the main thread for the Downloader.
/// This thread is responsible for queuing up downloads and other goodness.
/// </summary>
/// <param name="intent">
/// The intent that was recieved.
/// </param>
protected override void OnHandleIntent(Intent intent)
{
Log.Debug(Tag,"DownloaderService.OnHandleIntent");
this.IsServiceRunning = true;
try
{
var pendingIntent = (PendingIntent)intent.GetParcelableExtra(DownloaderServiceExtras.PendingIntent);
if (null != pendingIntent)
{
this.downloadNotification.PendingIntent = pendingIntent;
this.pPendingIntent = pendingIntent;
}
else if (null != this.pPendingIntent)
{
this.downloadNotification.PendingIntent = this.pPendingIntent;
}
else
{
Log.Debug(Tag,"LVLDL Downloader started in bad state without notification intent.");
return;
}
// when the LVL check completes, a successful response will update the service
if (IsLvlCheckRequired(this.packageInfo))
{
this.UpdateLvl(this);
return;
}
// get each download
List<DownloadInfo> infos = DownloadsDatabase.GetDownloads();
this.BytesSoFar = 0;
this.TotalLength = 0;
this.fileCount = infos.Count();
foreach (DownloadInfo info in infos)
{
// We do an (simple) integrity check on each file, just to
// make sure and to verify that the file matches the state
if (info.Status == ExpansionDownloadStatus.Success
&& !Helpers.DoesFileExist(this, info.FileName, info.TotalBytes, true))
{
info.Status = ExpansionDownloadStatus.None;
info.CurrentBytes = 0;
}
// get aggregate data
this.TotalLength += info.TotalBytes;
this.BytesSoFar += info.CurrentBytes;
}
this.PollNetworkState();
if (this.connectionReceiver == null)
{
// We use this to track network state, such as when WiFi, Cellular, etc. is enabled
// when downloads are paused or in progress.
this.connectionReceiver = new InnerBroadcastReceiver(this);
var intentFilter = new IntentFilter(ConnectivityManager.ConnectivityAction);
intentFilter.AddAction(WifiManager.WifiStateChangedAction);
this.RegisterReceiver(this.connectionReceiver, intentFilter);
}
// loop through all downloads and fetch them
int types = Enum.GetValues(typeof(ApkExpansionPolicy.ExpansionFileType)).Length;
for (int index = 0; index < types; index++)
{
DownloadInfo info = infos[index];
Log.Debug(Tag,"Starting download of " + info.FileName);
long startingCount = info.CurrentBytes;
if (info.Status != ExpansionDownloadStatus.Success)
{
var dt = new DownloadThread(info, this, this.downloadNotification);
this.CancelAlarms();
this.ScheduleAlarm(ActiveThreadWatchdog);
dt.Run();
this.CancelAlarms();
}
DownloadsDatabase.UpdateFromDatabase(ref info);
bool setWakeWatchdog = false;
DownloaderState notifyStatus;
switch (info.Status)
{
case ExpansionDownloadStatus.Forbidden:
// the URL is out of date
this.UpdateLvl(this);
return;
case ExpansionDownloadStatus.Success:
this.BytesSoFar += info.CurrentBytes - startingCount;
if (index < infos.Count() - 1)
{
continue;
}
DownloadsDatabase.UpdateMetadata(this.packageInfo.VersionCode, ExpansionDownloadStatus.None);
this.downloadNotification.OnDownloadStateChanged(DownloaderState.Completed);
return;
case ExpansionDownloadStatus.FileDeliveredIncorrectly:
// we may be on a network that is returning us a web page on redirect
notifyStatus = DownloaderState.PausedNetworkSetupFailure;
info.CurrentBytes = 0;
DownloadsDatabase.UpdateDownload(info);
setWakeWatchdog = true;
break;
case ExpansionDownloadStatus.PausedByApp:
notifyStatus = DownloaderState.PausedByRequest;
break;
case ExpansionDownloadStatus.WaitingForNetwork:
case ExpansionDownloadStatus.WaitingToRetry:
notifyStatus = DownloaderState.PausedNetworkUnavailable;
setWakeWatchdog = true;
break;
case ExpansionDownloadStatus.QueuedForWifi:
case ExpansionDownloadStatus.QueuedForWifiOrCellularPermission:
// look for more detail here
notifyStatus = this.wifiManager != null && !this.wifiManager.IsWifiEnabled
? DownloaderState.PausedWifiDisabledNeedCellularPermission
: DownloaderState.PausedNeedCellularPermission;
setWakeWatchdog = true;
break;
case ExpansionDownloadStatus.Canceled:
notifyStatus = DownloaderState.FailedCanceled;
setWakeWatchdog = true;
break;
case ExpansionDownloadStatus.InsufficientSpaceError:
notifyStatus = DownloaderState.FailedSdCardFull;
setWakeWatchdog = true;
break;
case ExpansionDownloadStatus.DeviceNotFoundError:
notifyStatus = DownloaderState.PausedSdCardUnavailable;
setWakeWatchdog = true;
break;
default:
notifyStatus = DownloaderState.Failed;
break;
}
if (setWakeWatchdog)
{
this.ScheduleAlarm(WatchdogWakeTimer);
}
else
{
this.CancelAlarms();
}