summaryrefslogtreecommitdiff
path: root/Tizen.Applications.PackageManager/Tizen.Applications/PackageManager.cs
blob: b7f37ef21fb5b9f50bab83105b616e30728b009c (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
/*
 * Copyright (c) 2016 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Licensed under the Apache License, Version 2.0 (the License);
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an AS IS BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.IO;

namespace Tizen.Applications
{
    /// <summary>
    /// PackageManager class. This class has the methods and events of the PackageManager.
    /// </summary>
    /// <remarks>
    /// The package manager is one of the core modules of Tizen application framework, and responsible for getting their information.
    /// You can also retrieve information related to the packages that are installed on the device.
    /// </remarks>
    public static class PackageManager
    {
        private const string LogTag = "Tizen.Applications.PackageManager";

        private static SafePackageManagerHandle s_handle = new SafePackageManagerHandle();
        private static Interop.PackageManager.EventStatus s_eventStatus = Interop.PackageManager.EventStatus.All;
        private static event EventHandler<PackageManagerEventArgs> s_installEventHandler;
        private static event EventHandler<PackageManagerEventArgs> s_uninstallEventHandler;
        private static event EventHandler<PackageManagerEventArgs> s_updateEventHandler;
        private static event EventHandler<PackageManagerEventArgs> s_moveEventHandler;
        private static event EventHandler<PackageManagerEventArgs> s_clearDataEventHandler;

        private static Interop.PackageManager.PackageManagerEventCallback s_packageManagerEventCallback;

        /// <summary>
        /// Event Callback Method for the request.
        /// </summary>
        /// <param name="type">Type of the package which was requested</param>
        /// <param name="packageId">ID of the package which was requested</param>
        /// <param name="eventType">Event type of the request</param>
        /// <param name="eventState">Current event state of the request</param>
        /// <param name="progress">Progress for the request being processed by the package manager (in percent)</param>
        public delegate void RequestEventCallback(string type, string packageId, PackageEventType eventType, PackageEventState eventState, int progress);

        private static Dictionary<int, RequestEventCallback> RequestCallbacks = new Dictionary<int, RequestEventCallback>();
        private static Dictionary<int, SafePackageManagerRequestHandle> RequestHandles = new Dictionary<int, SafePackageManagerRequestHandle>();

        private delegate Interop.PackageManager.ErrorCode InstallMethodWithCallback(SafePackageManagerRequestHandle requestHandle, string pkgPath, Interop.PackageManager.PackageManagerRequestEventCallback requestCallback, IntPtr userData, out int requestID);
        private delegate Interop.PackageManager.ErrorCode InstallMethod(SafePackageManagerRequestHandle requestHandle, string pkgPath, out int requestID);

        /// <summary>
        /// InstallProgressChanged event. This event is occurred when a package is getting installed and the progress of the request to the package manager changes.
        /// </summary>
        public static event EventHandler<PackageManagerEventArgs> InstallProgressChanged
        {
            add
            {
                SetPackageManagerEventStatus(Interop.PackageManager.EventStatus.Install);
                RegisterPackageManagerEventIfNeeded();
                s_installEventHandler += value;
            }
            remove
            {
                s_installEventHandler -= value;
                UnregisterPackageManagerEventIfNeeded();
                UnsetPackageManagerEventStatus();
            }
        }

        /// <summary>
        /// UninstallProgressChanged event. This event is occurred when a package is getting uninstalled and the progress of the request to the package manager changes.
        /// </summary>
        public static event EventHandler<PackageManagerEventArgs> UninstallProgressChanged
        {
            add
            {
                SetPackageManagerEventStatus(Interop.PackageManager.EventStatus.Uninstall);
                RegisterPackageManagerEventIfNeeded();
                s_uninstallEventHandler += value;
            }
            remove
            {
                s_uninstallEventHandler -= value;
                UnregisterPackageManagerEventIfNeeded();
                UnsetPackageManagerEventStatus();
            }
        }

        /// <summary>
        /// UpdateProgressChanged event. This event is occurred when a package is getting updated and the progress of the request to the package manager changes.
        /// </summary>
        public static event EventHandler<PackageManagerEventArgs> UpdateProgressChanged
        {
            add
            {
                SetPackageManagerEventStatus(Interop.PackageManager.EventStatus.Upgrade);
                RegisterPackageManagerEventIfNeeded();
                s_updateEventHandler += value;
            }
            remove
            {
                s_updateEventHandler -= value;
                UnregisterPackageManagerEventIfNeeded();
                UnsetPackageManagerEventStatus();
            }
        }

        /// <summary>
        /// MoveProgressChanged event. This event is occurred when a package is getting moved and the progress of the request to the package manager changes.
        /// </summary>
        public static event EventHandler<PackageManagerEventArgs> MoveProgressChanged
        {
            add
            {
                SetPackageManagerEventStatus(Interop.PackageManager.EventStatus.Move);
                RegisterPackageManagerEventIfNeeded();
                s_moveEventHandler += value;
            }
            remove
            {
                s_moveEventHandler -= value;
                UnregisterPackageManagerEventIfNeeded();
                UnsetPackageManagerEventStatus();
            }
        }

        /// <summary>
        /// ClearDataProgressChanged event. This event is occurred when data directories are cleared in the given package.
        /// </summary>
        public static event EventHandler<PackageManagerEventArgs> ClearDataProgressChanged
        {
            add
            {
                SetPackageManagerEventStatus(Interop.PackageManager.EventStatus.ClearData);
                RegisterPackageManagerEventIfNeeded();
                s_clearDataEventHandler += value;
            }
            remove
            {
                s_clearDataEventHandler -= value;
                UnregisterPackageManagerEventIfNeeded();
                UnsetPackageManagerEventStatus();
            }
        }

        private static SafePackageManagerHandle Handle
        {
            get
            {
                if (s_handle.IsInvalid)
                {
                    var err = Interop.PackageManager.PackageManagerCreate(out s_handle);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to create package manager handle. err = {0}", err));
                    }
                }
                return s_handle;
            }
        }

        private static Interop.PackageManager.PackageManagerRequestEventCallback internalRequestEventCallback = (id, packageType, packageId, eventType, eventState, progress, error, userData) =>
        {
            if (RequestCallbacks.ContainsKey(id))
            {
                try
                {
                    RequestCallbacks[id](packageType, packageId, (PackageEventType)eventType, (PackageEventState)eventState, progress);
                    if (eventState == Interop.PackageManager.PackageEventState.Completed || eventState == Interop.PackageManager.PackageEventState.Failed)
                    {
                        Log.Debug(LogTag, string.Format("release request handle for id : {0}", id));
                        RequestHandles[id].Dispose();
                        RequestHandles.Remove(id);
                        RequestCallbacks.Remove(id);
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(LogTag, e.Message);
                    RequestHandles[id].Dispose();
                    RequestHandles.Remove(id);
                    RequestCallbacks.Remove(id);
                }
            }
        };

        /// <summary>
        /// Gets the package ID for the given app ID.
        /// </summary>
        /// <param name="applicationId">The ID of the application</param>
        /// <returns>Returns the ID of the package. Empty string if App ID does not exist</returns>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        public static string GetPackageIdByApplicationId(string applicationId)
        {
            string packageId;
            var err = Interop.PackageManager.PackageManageGetPackageIdByAppId(applicationId, out packageId);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to get package Id of {0}. err = {1}", applicationId, err));
                if (err != Interop.PackageManager.ErrorCode.InvalidParameter)
                {
                    throw PackageManagerErrorFactory.GetException(err, "Failed to get package Id");
                }
            }
            return packageId;
        }

        /// <summary>
        /// Gets the package information for the given package.
        /// </summary>
        /// <param name="packageId">The ID of the package</param>
        /// <returns>Returns the package information for the given package ID.</returns>
        /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        public static Package GetPackage(string packageId)
        {
            return Package.GetPackage(packageId);
        }

        /// <summary>
        /// Clears the application's internal and external cache directory.
        /// </summary>
        /// <param name="packageId">Id of the package</param>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
        /// <privilege>http://tizen.org/privilege/packagemanager.clearcache</privilege>
        public static void ClearCacheDirectory(string packageId)
        {
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerClearCacheDir(packageId);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to clear cache directory for {0}. err = {1}", packageId, err));
                throw PackageManagerErrorFactory.GetException(err, "Failed to clear cache directory");
            }
        }

        /// <summary>
        /// Clears all application's internal and external cache directory.
        /// </summary>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static void ClearAllCacheDirectory()
        {
            var err = Interop.PackageManager.PackageManagerClearAllCacheDir();
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to clear all cache directories. err = {0}", err));
                throw PackageManagerErrorFactory.GetException(err, "Failed to clear all cache directories");
            }
        }

        /// <summary>
        /// Clears the application's internal and external data directories
        /// </summary>
        /// <remarks>
        /// All files under data, shared/data and shared/trusted in the internal storage are removed.
        /// And, If external storeage exists, then all files under data and shared/trusted in the external storage are removed.
        /// </remarks>
        /// <param name="packageId">Id of the package</param>
        /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static void ClearDataDirectory(string packageId)
        {
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerClearDataDir(packageId);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to clear data directory for {0}. err = {1}", packageId, err));
                throw PackageManagerErrorFactory.GetException(err, "Failed to clear data directory");
            }
        }

        /// <summary>
        /// Retrieves package information of all installed packages.
        /// </summary>
        /// <returns>Returns the list of packages.</returns>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        public static IEnumerable<Package> GetPackages()
        {
            return GetPackages(null);
        }

        /// <summary>
        /// Retrieves package information of all installed packages satisfying filter conditions.
        /// </summary>
        /// <param name="filter">Optional - package filters</param>
        /// <returns>Returns the list of packages.</returns>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        public static IEnumerable<Package> GetPackages(PackageFilter filter)
        {
            List<Package> packageList = new List<Package>();

            IntPtr filterHandle;
            var err = Interop.PackageManager.PackageManagerFilterCreate(out filterHandle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to create package filter handle. err = {0}", err));
                return packageList;
            }

            if (filter != null && filter.Filters != null)
            {
                foreach (KeyValuePair<string, bool> entry in filter?.Filters)
                {
                    err = Interop.PackageManager.PackageManagerFilterAdd(filterHandle, entry.Key, entry.Value);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to configure package filter. err = {0}", err));
                        break;
                    }
                }
            }

            if (err == Interop.PackageManager.ErrorCode.None)
            {
                Interop.PackageManager.PackageManagerPackageInfoCallback cb = (handle, userData) =>
                {
                    packageList.Add(Package.GetPackage(handle));
                    return true;
                };

                err = Interop.PackageManager.PackageManagerFilterForeachPackageInfo(filterHandle, cb, IntPtr.Zero);
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    Log.Warn(LogTag, string.Format("Failed to get package Informations. err = {0}", err));
                }
            }

            err = Interop.PackageManager.PackageManagerFilterDestroy(filterHandle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to destroy package filter handle. err = {0}", err));
            }
            return packageList;
        }

        /// <summary>
        /// Gets the total package size information.
        /// </summary>
        /// <returns>Returns the total package size information asynchronously.</returns>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        public static async Task<PackageSizeInformation> GetTotalSizeInformationAsync()
        {
            TaskCompletionSource<PackageSizeInformation> tcs = new TaskCompletionSource<PackageSizeInformation>();
            Interop.PackageManager.PackageManagerTotalSizeInfoCallback cb = (handle, userData) =>
            {
                if (handle != IntPtr.Zero)
                {
                    tcs.TrySetResult(PackageSizeInformation.GetPackageSizeInformation(handle));
                }
            };

            var err = Interop.PackageManager.PackageManagerGetTotalSizeInfo(cb, IntPtr.Zero);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                tcs.TrySetException(PackageManagerErrorFactory.GetException(err, "Failed to get total package size info"));
            }
            return await tcs.Task.ConfigureAwait(false);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, null, PackageType.UNKNOWN, null, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="eventCallback">The event callback will be invoked only for the current request</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, RequestEventCallback eventCallback, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, null, PackageType.UNKNOWN, eventCallback, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="type">Package type for the package to be installed</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, PackageType type, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, null, type, null, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="expansionPackagePath">Absolute path for the expansion package to be installed</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, string expansionPackagePath, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, expansionPackagePath, PackageType.UNKNOWN, null, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="type">Package type for the package to be installed</param>
        /// <param name="eventCallback">The event callback will be invoked only for the current request</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, PackageType type, RequestEventCallback eventCallback, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, null, type, eventCallback, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="expansionPackagePath">Absolute path for the expansion package to be installed</param>
        /// <param name="eventCallback">The event callback will be invoked only for the current request</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, string expansionPackagePath, RequestEventCallback eventCallback, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, expansionPackagePath, PackageType.UNKNOWN, eventCallback, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="expansionPackagePath">Absolute path for the expansion package to be installed</param>
        /// <param name="type">Package type for the package to be installed</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, string expansionPackagePath, PackageType type, InstallationMode installMode = InstallationMode.Normal)
        {
            return Install(packagePath, expansionPackagePath, type, null, installMode);
        }

        /// <summary>
        /// Installs package located at the given path
        /// </summary>
        /// <param name="packagePath">Absolute path for the package to be installed</param>
        /// <param name="expansionPackagePath">Absolute path for the expansion package to be installed</param>
        /// <param name="type">Package type for the package to be installed</param>
        /// <param name="eventCallback">The event callback will be invoked only for the current request</param>
        /// <param name="installMode">Optional parameter to indicate special installation mode</param>
        /// <returns>Returns true if installtion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of installation is seccessful.
        /// To check the result of installation, the caller should check the progress using InstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Install(string packagePath, string expansionPackagePath, PackageType type, RequestEventCallback eventCallback, InstallationMode installMode = InstallationMode.Normal)
        {
            SafePackageManagerRequestHandle RequestHandle;
            var err = Interop.PackageManager.PackageManagerRequestCreate(out RequestHandle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to install package {0}. Error in creating package manager request handle. err = {1}", packagePath, err));
                return false;
            }

            try
            {
                if (type != PackageType.UNKNOWN)
                {
                    err = Interop.PackageManager.PackageManagerRequestSetType(RequestHandle, type.ToString().ToLower());
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to install package {0}. Error in setting request package type. err = {1}", packagePath, err));
                        RequestHandle.Dispose();
                        return false;
                    }
                }

                if (!string.IsNullOrEmpty(expansionPackagePath))
                {
                    err = Interop.PackageManager.PackageManagerRequestSetTepPath(RequestHandle, expansionPackagePath);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to install package {0}. Error in setting request package mode. err = {1}", packagePath, err));
                        RequestHandle.Dispose();
                        return false;
                    }
                }

                int requestId;
                if (eventCallback != null)
                {
                    InstallMethodWithCallback install;
                    if (installMode == InstallationMode.Mount)
                    {
                        install = Interop.PackageManager.PackageManagerRequestMountInstallWithCB;
                    }
                    else
                    {
                        install = Interop.PackageManager.PackageManagerRequestInstallWithCB;
                    }
                    err = install(RequestHandle, packagePath, internalRequestEventCallback, IntPtr.Zero, out requestId);
                    if (err == Interop.PackageManager.ErrorCode.None)
                    {
                        RequestCallbacks.Add(requestId, eventCallback);
                        RequestHandles.Add(requestId, RequestHandle);
                    }
                    else
                    {
                        Log.Warn(LogTag, string.Format("Failed to install package {0}. err = {1}", packagePath, err));
                        RequestHandle.Dispose();
                        return false;
                    }
                }
                else
                {
                    InstallMethod install;
                    if (installMode == InstallationMode.Mount)
                    {
                        install = Interop.PackageManager.PackageManagerRequestMountInstall;
                    }
                    else
                    {
                        install = Interop.PackageManager.PackageManagerRequestInstall;
                    }
                    err = install(RequestHandle, packagePath, out requestId);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to install package {0}. err = {1}", packagePath, err));
                        RequestHandle.Dispose();
                        return false;
                    }
                    // RequestHandle isn't necessary when this method is called without 'eventCallback' parameter.
                    RequestHandle.Dispose();
                }
                return true;
            }
            catch (Exception e)
            {
                Log.Warn(LogTag, e.Message);
                RequestHandle.Dispose();
                return false;
            }
        }

        /// <summary>
        /// Uninstalls package with the given name.
        /// </summary>
        /// <param name="packageId">Id of the package to be uninstalled</param>
        /// <returns>Returns true if uninstallation request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of uninstallation is seccessful.
        /// To check the result of uninstallation, the caller should check the progress using UninstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Uninstall(string packageId)
        {
            return Uninstall(packageId, PackageType.UNKNOWN, null);
        }

        /// <summary>
        /// Uninstalls package with the given name.
        /// </summary>
        /// <param name="packageId">Id of the package to be uninstalled</param>
        /// <param name="type">Optional - Package type for the package to be uninstalled</param>
        /// <returns>Returns true if uninstalltion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of uninstallation is seccessful.
        /// To check the result of uninstallation, the caller should check the progress using UninstallProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Uninstall(string packageId, PackageType type)
        {
            return Uninstall(packageId, type, null);
        }

        /// <summary>
        /// Uninstalls package with the given name.
        /// </summary>
        /// <param name="packageId">Id of the package to be uninstalled</param>
        /// <param name="eventCallback">Optional - The event callback will be invoked only for the current request</param>
        /// <returns>Returns true if uninstalltion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of uninstallation is seccessful.
        /// To check the result of uninstallation, the caller should check the progress using UninstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Uninstall(string packageId, RequestEventCallback eventCallback)
        {
            return Uninstall(packageId, PackageType.UNKNOWN, eventCallback);
        }

        /// <summary>
        /// Uninstalls package with the given name.
        /// </summary>
        /// <param name="packageId">Id of the package to be uninstalled</param>
        /// <param name="type">Optional - Package type for the package to be uninstalled</param>
        /// <param name="eventCallback">Optional - The event callback will be invoked only for the current request</param>
        /// <returns>Returns true if uninstalltion request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of uninstallation is seccessful.
        /// To check the result of uninstallation, the caller should check the progress using UninstallProgressChanged event OR eventCallback.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Uninstall(string packageId, PackageType type, RequestEventCallback eventCallback)
        {
            SafePackageManagerRequestHandle RequestHandle;
            var err = Interop.PackageManager.PackageManagerRequestCreate(out RequestHandle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to uninstall package {0}. Error in creating package manager request handle. err = {1}", packageId, err));
                return false;
            }

            try
            {
                err = Interop.PackageManager.PackageManagerRequestSetType(RequestHandle, type.ToString().ToLower());
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    Log.Warn(LogTag, string.Format("Failed to uninstall package {0}. Error in setting request package type. err = {1}", packageId, err));
                    RequestHandle.Dispose();
                    return false;
                }

                int requestId;
                if (eventCallback != null)
                {
                    err = Interop.PackageManager.PackageManagerRequestUninstallWithCB(RequestHandle, packageId, internalRequestEventCallback, IntPtr.Zero, out requestId);
                    if (err == Interop.PackageManager.ErrorCode.None)
                    {
                        RequestCallbacks.Add(requestId, eventCallback);
                        RequestHandles.Add(requestId, RequestHandle);
                    }
                    else
                    {
                        Log.Warn(LogTag, string.Format("Failed to uninstall package {0}. err = {1}", packageId, err));
                        RequestHandle.Dispose();
                        return false;
                    }
                }
                else
                {
                    err = Interop.PackageManager.PackageManagerRequestUninstall(RequestHandle, packageId, out requestId);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to uninstall package. err = {0}", err));
                        RequestHandle.Dispose();
                        return false;
                    }
                    // RequestHandle isn't necessary when this method is called without 'eventCallback' parameter.
                    RequestHandle.Dispose();
                }
                return true;
            }
            catch (Exception e)
            {
                Log.Warn(LogTag, e.Message);
                RequestHandle.Dispose();
                return false;
            }
        }

        /// <summary>
        /// Move package to given storage.
        /// </summary>
        /// <param name="packageId">Id of the package to be moved</param>
        /// <param name="newStorage">Storage, package should be moved to</param>
        /// <returns>Returns true if move request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of move is seccessful.
        /// To check the result of move, the caller should check the progress using MoveProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Move(string packageId, StorageType newStorage)
        {
            return Move(packageId, PackageType.UNKNOWN, newStorage, null);
        }

        /// <summary>
        /// Move package to given storage.
        /// </summary>
        /// <param name="packageId">Id of the package to be moved</param>
        /// <param name="type">Optional - Package type for the package to be moved</param>
        /// <param name="newStorage">Storage, package should be moved to</param>
        /// <returns>Returns true if move request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of move is seccessful.
        /// To check the result of move, the caller should check the progress using MoveProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Move(string packageId, PackageType type, StorageType newStorage)
        {
            return Move(packageId, type, newStorage, null);
        }

        /// <summary>
        /// Move package to given storage.
        /// </summary>
        /// <param name="packageId">Id of the package to be moved</param>
        /// <param name="newStorage">Storage, package should be moved to</param>
        /// <param name="eventCallback">Optional - The event callback will be invoked only for the current request</param>
        /// <returns>Returns true if move request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of move is seccessful.
        /// To check the result of move, the caller should check the progress using MoveProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Move(string packageId, StorageType newStorage, RequestEventCallback eventCallback)
        {
            return Move(packageId, PackageType.UNKNOWN, newStorage, eventCallback);
        }

        /// <summary>
        /// Move package to given storage.
        /// </summary>
        /// <param name="packageId">Id of the package to be moved</param>
        /// <param name="type">Optional - Package type for the package to be moved</param>
        /// <param name="newStorage">Storage, package should be moved to</param>
        /// <param name="eventCallback">Optional - The event callback will be invoked only for the current request</param>
        /// <returns>Returns true if move request is successful, false otherwise.</returns>
        /// <remarks>
        /// The 'true' means that just the request of move is seccessful.
        /// To check the result of move, the caller should check the progress using MoveProgressChanged event.
        /// </remarks>
        /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
        /// <privlevel>platform</privlevel>
        public static bool Move(string packageId, PackageType type, StorageType newStorage, RequestEventCallback eventCallback)
        {
            SafePackageManagerRequestHandle RequestHandle;
            var err = Interop.PackageManager.PackageManagerRequestCreate(out RequestHandle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to create package manager request handle. err = {0}", err));
                return false;
            }

            try
            {
                bool result = true;
                err = Interop.PackageManager.PackageManagerRequestSetType(RequestHandle, type.ToString().ToLower());
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    Log.Warn(LogTag, string.Format("Failed to move package. Error in setting request package type. err = {0}", err));
                    RequestHandle.Dispose();
                    return false;
                }

                if (eventCallback != null)
                {
                    int requestId;
                    err = Interop.PackageManager.PackageManagerRequestMoveWithCB(RequestHandle, packageId, (Interop.PackageManager.StorageType)newStorage, internalRequestEventCallback, IntPtr.Zero, out requestId);
                    if (err == Interop.PackageManager.ErrorCode.None)
                    {
                        RequestCallbacks.Add(requestId, eventCallback);
                        RequestHandles.Add(requestId, RequestHandle);
                    }
                    else
                    {
                        Log.Warn(LogTag, string.Format("Failed to move package to requested location. err = {0}", err));
                        RequestHandle.Dispose();
                        result = false;
                    }
                }
                else
                {
                    err = Interop.PackageManager.PackageManagerRequestMove(RequestHandle, packageId, (Interop.PackageManager.StorageType)newStorage);
                    if (err != Interop.PackageManager.ErrorCode.None)
                    {
                        Log.Warn(LogTag, string.Format("Failed to move package to requested location. err = {0}", err));
                        RequestHandle.Dispose();
                        result = false;
                    }
                    // RequestHandle isn't necessary when this method is called without 'eventCallback' parameter.
                    RequestHandle.Dispose();
                }
                return result;
            }
            catch (Exception e)
            {
                Log.Warn(LogTag, e.Message);
                RequestHandle.Dispose();
                return false;
            }
        }

        /// <summary>
        /// Gets permission type of package which has given application id
        /// </summary>
        /// <param name="applicationId">Id of the application</param>
        /// <returns>Returns permission type.</returns>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        public static PermissionType GetPermissionTypeByApplicationId(string applicationId)
        {
            Interop.PackageManager.PackageManagerPermissionType permissionType;
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerGetPermissionType(applicationId, out permissionType);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                throw PackageManagerErrorFactory.GetException(err, "Failed to get permission type.");
            }

            return (PermissionType)permissionType;
        }

        /// <summary>
        /// Gets package's preload attribute which contain given applicion id
        /// </summary>
        /// <param name="applicationId">Id of the application</param>
        /// <returns>Returns true if package is preloaded. Otherwise return false.</returns>
        /// <privilege>http://tizen.org/privilege/packagemanager.info</privilege>
        /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
        /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
        public static bool IsPreloadPackageByApplicationId(string applicationId)
        {
            bool isPreloadPackage;
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerIsPreloadPackageByApplicationId(applicationId, out isPreloadPackage);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                throw PackageManagerErrorFactory.GetException(err, "Failed to get preload info");
            }

            return isPreloadPackage;
        }

        /// <summary>
        /// Compare certificate of two packages
        /// </summary>
        /// <param name="lhsPackageId">package id to compare</param>
        /// <param name="rhsPackageId">package id to be compared</param>
        /// <returns>Returns certificate comparison result.</returns>
        /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        public static CertCompareResultType CompareCertInfo(string lhsPackageId, string rhsPackageId)
        {
            Interop.PackageManager.CertCompareResultType compareResult;
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerCompareCertInfo(lhsPackageId, rhsPackageId, out compareResult);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                throw PackageManagerErrorFactory.GetException(err, "Failed to compare cert info");
            }

            return (CertCompareResultType)compareResult;
        }

        /// <summary>
        /// Compare certificate of two packages which contain each given application id
        /// </summary>
        /// <param name="lhsApplicationId">application id to compare</param>
        /// <param name="rhsApplicationId">application id to be compared</param>
        /// <returns>Returns certificate comparison result.</returns>
        /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
        /// <exception cref="System.IO.IOException">Thrown when method failed due to internal IO error</exception>
        public static CertCompareResultType CompareCertInfoByApplicationId(string lhsApplicationId, string rhsApplicationId)
        {
            Interop.PackageManager.CertCompareResultType compareResult;
            Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerCompareCertInfoByApplicationId(lhsApplicationId, rhsApplicationId, out compareResult);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                throw PackageManagerErrorFactory.GetException(err, "Failed to compare cert info by application id");
            }

            return (CertCompareResultType)compareResult;
        }

        /// <summary>
        /// Drm nested class. This class has the PackageManager's drm related methods.
        /// </summary>
        public static class Drm
        {
            /// <summary>
            /// Generates request for getting license
            /// </summary>
            /// <param name="responseData">Response data string of the purchase request</param>
            /// <returns>Returns package drm information of given response data which contains require data and license url</returns>
            /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
            /// <privlevel>platform</privlevel>
            /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
            /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
            /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
            /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
            public static PackageDrm GenerateLicenseRequest(string responseData)
            {
                return PackageDrm.GenerateLicenseRequest(responseData);

            }

            /// <summary>
            /// Registers encrypted license
            /// </summary>
            /// <param name="responseData">The response data string of the rights request</param>
            /// <returns>Returns true if succeed. Otherwise return false</returns>
            /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
            /// <privlevel>platform</privlevel>
            /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
            /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
            /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
            /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
            public static bool RegisterLicense(string responseData)
            {
                Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerDrmRegisterLicense(responseData);
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    throw PackageManagerErrorFactory.GetException(err, "Failed to register drm license");
                }

                return true;
            }

            /// <summary>
            /// Decrypts contents which is encrypted
            /// </summary>
            /// <param name="drmFilePath">Drm file path</param>
            /// <param name="decryptedFilePath">Decrypted file path</param>
            /// <returns>Returns true if succeed. Otherwise return false</returns>
            /// <privilege>http://tizen.org/privilege/packagemanager.admin</privilege>
            /// <privlevel>platform</privlevel>
            /// <exception cref="ArgumentException">Thrown when failed when input package ID is invalid</exception>
            /// <exception cref="OutOfMemoryException">Thrown when there is not enough memory to continue the execution of the method</exception>
            /// <exception cref="UnauthorizedAccessException">Thrown when app does not have privilege to access this method</exception>
            /// <exception cref="SystemException">Thrown when method failed due to internal system error</exception>
            public static bool DecryptPackage(string drmFilePath, string decryptedFilePath)
            {
                Interop.PackageManager.ErrorCode err = Interop.PackageManager.PackageManagerDrmDecryptPackage(drmFilePath, decryptedFilePath);
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    throw PackageManagerErrorFactory.GetException(err, "Failed to decrypt drm package");
                }

                return true;
            }
        }

        private static void SetPackageManagerEventStatus(Interop.PackageManager.EventStatus status)
        {
            if (Handle.IsInvalid) return;

            Interop.PackageManager.EventStatus eventStatus = s_eventStatus;
            eventStatus |= status;
            if (eventStatus != Interop.PackageManager.EventStatus.All)
                eventStatus |= Interop.PackageManager.EventStatus.Progress;

            var err = Interop.PackageManager.ErrorCode.None;
            if (s_eventStatus != eventStatus)
            {
                err = Interop.PackageManager.PackageManagerSetEvenStatus(Handle, eventStatus);
                if (err == Interop.PackageManager.ErrorCode.None)
                {
                    s_eventStatus = eventStatus;
                    Log.Debug(LogTag, string.Format("New Event Status flag: {0}", s_eventStatus));
                    return;
                }
                Log.Debug(LogTag, string.Format("Failed to set flag for {0} event. err = {1}", eventStatus, err));
            }
        }

        private static void UnsetPackageManagerEventStatus()
        {
            if (Handle.IsInvalid) return;

            Interop.PackageManager.EventStatus eventStatus = Interop.PackageManager.EventStatus.All;
            if (s_installEventHandler != null) eventStatus |= Interop.PackageManager.EventStatus.Install;
            if (s_uninstallEventHandler != null) eventStatus |= Interop.PackageManager.EventStatus.Uninstall;
            if (s_updateEventHandler != null) eventStatus |= Interop.PackageManager.EventStatus.Upgrade;
            if (s_moveEventHandler != null) eventStatus |= Interop.PackageManager.EventStatus.Move;
            if (s_clearDataEventHandler != null) eventStatus |= Interop.PackageManager.EventStatus.ClearData;
            if (eventStatus != Interop.PackageManager.EventStatus.All)
                eventStatus |= Interop.PackageManager.EventStatus.Progress;

            var err = Interop.PackageManager.ErrorCode.None;
            if (s_eventStatus != eventStatus)
            {
                err = Interop.PackageManager.PackageManagerSetEvenStatus(Handle, eventStatus);
                if (err == Interop.PackageManager.ErrorCode.None)
                {
                    s_eventStatus = eventStatus;
                    Log.Debug(LogTag, string.Format("New Event Status flag: {0}", s_eventStatus));
                    return;
                }
                Log.Debug(LogTag, string.Format("Failed to set flag for {0} event. err = {1}", eventStatus, err));
            }
        }

        private static void RegisterPackageManagerEventIfNeeded()
        {
            if (s_installEventHandler != null && s_uninstallEventHandler != null && s_updateEventHandler != null && s_moveEventHandler != null && s_clearDataEventHandler != null)
            {
                return;
            }

            var err = Interop.PackageManager.ErrorCode.None;
            s_packageManagerEventCallback = (packageType, packageId, eventType, eventState, progress, error, user_data) =>
            {
                try
                {
                    if (eventType == Interop.PackageManager.EventType.Install)
                    {
                        s_installEventHandler?.Invoke(null, new PackageManagerEventArgs(packageType, packageId, (PackageEventState)eventState, progress));
                    }
                    else if (eventType == Interop.PackageManager.EventType.Uninstall)
                    {
                        s_uninstallEventHandler?.Invoke(null, new PackageManagerEventArgs(packageType, packageId, (PackageEventState)eventState, progress));
                    }
                    else if (eventType == Interop.PackageManager.EventType.Update)
                    {
                        s_updateEventHandler?.Invoke(null, new PackageManagerEventArgs(packageType, packageId, (PackageEventState)eventState, progress));
                    }
                    else if (eventType == Interop.PackageManager.EventType.Move)
                    {
                        s_moveEventHandler?.Invoke(null, new PackageManagerEventArgs(packageType, packageId, (PackageEventState)eventState, progress));
                    }
                    else if (eventType == Interop.PackageManager.EventType.ClearData)
                    {
                        s_clearDataEventHandler?.Invoke(null, new PackageManagerEventArgs(packageType, packageId, (PackageEventState)eventState, progress));
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(LogTag, e.Message);
                }
            };

            if (!Handle.IsInvalid)
            {
                Log.Debug(LogTag, "Reset Package Event");
                err = Interop.PackageManager.PackageManagerUnsetEvent(Handle);
                if (err != Interop.PackageManager.ErrorCode.None)
                {
                    throw PackageManagerErrorFactory.GetException(err, "Failed to unregister package manager event event.");
                }

                err = Interop.PackageManager.PackageManagerSetEvent(Handle, s_packageManagerEventCallback, IntPtr.Zero);
            }
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                Log.Warn(LogTag, string.Format("Failed to register callback for package manager event. err = {0}", err));
            }
        }

        private static void UnregisterPackageManagerEventIfNeeded()
        {
            if (Handle.IsInvalid || s_installEventHandler != null || s_uninstallEventHandler != null || s_updateEventHandler != null || s_moveEventHandler != null || s_clearDataEventHandler != null)
            {
                return;
            }

            var err = Interop.PackageManager.PackageManagerUnsetEvent(Handle);
            if (err != Interop.PackageManager.ErrorCode.None)
            {
                throw PackageManagerErrorFactory.GetException(err, "Failed to unregister package manager event event.");
            }
        }
    }

    internal static class PackageManagerErrorFactory
    {
        internal static Exception GetException(Interop.PackageManager.ErrorCode err, string message)
        {
            string errMessage = string.Format("{0} err = {1}", message, err);
            switch (err)
            {
                case Interop.PackageManager.ErrorCode.InvalidParameter:
                case Interop.PackageManager.ErrorCode.NoSuchPackage:
                    return new ArgumentException(errMessage);
                case Interop.PackageManager.ErrorCode.PermissionDenied:
                    return new UnauthorizedAccessException(errMessage);
                case Interop.PackageManager.ErrorCode.IoError:
                    return new global::System.IO.IOException(errMessage);
                default:
                    return new InvalidOperationException(errMessage);
            }
        }
    }
}