public Task <bool> checkIfNotificationsSupported()
        {
            return(Task.Run(() =>
            {
                var context = GlobalSettings.GetContext;
                AppOpsManager mAppOps = (AppOpsManager)context.GetSystemService(global::Android.Content.Context.AppOpsService);
                ApplicationInfo appInfo = context.ApplicationInfo;
                String pkg = context.ApplicationContext.PackageName;
                int uid = appInfo.Uid;
                try
                {
                    var appOpsClass = Java.Lang.Class.ForName("android.app.AppOpsManager");
                    var checkOpNoThrowMethod = appOpsClass.GetMethod(CHECK_OP_NO_THROW, Java.Lang.Integer.Type, Java.Lang.Integer.Type, new Java.Lang.String().Class);                    //need to add String.Type

                    var opPostNotificationValue = appOpsClass.GetDeclaredField(OP_POST_NOTIFICATION);
                    var value = (int)opPostNotificationValue.GetInt(Java.Lang.Integer.Type);
                    var mode = (int)checkOpNoThrowMethod.Invoke(mAppOps, value, uid, pkg);
                    return (mode == (int)AppOpsManagerMode.Allowed);
                }
                catch (Exception)
                {
                    System.Diagnostics.Debug.WriteLine("Notification services is off or not supported");
                    return false;
                }
            }));
        }
Ejemplo n.º 2
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            UserDialogs.Init(this);
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Rg.Plugins.Popup.Popup.Init(this, savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            LoadApplication(new App());
            Instance = this;

            App.ClockPageChanged += SetService;
            // 注册DependencyService接口实现
            Xamarin.Forms.DependencyService.Register <OpenAppService>();
            Xamarin.Forms.DependencyService.Register <ToastService>();
            // 注册广播
            restartMsgReceiver = new RestartMsgReceiver();
            RegisterReceiver(restartMsgReceiver, new IntentFilter("com.companyname.ttp.ListenAppService"));

            MyTaskId = TaskId;

            // 获取本机所有应用
            App.AppManager.InitAllApps();
            // 检查PACKAGE_USAGE_STATS权限
            AppOpsManager appOps = (AppOpsManager)GetSystemService(AppOpsService);
            int           mode   = (int)appOps.CheckOpNoThrow("android:get_usage_stats", Process.MyUid(), PackageName);

            if (mode != (int)AppOpsManagerMode.Allowed)
            {
                AlertDialog.Builder builder     = new AlertDialog.Builder(this);
                AlertDialog         alertDialog = builder.SetTitle("请求权限")
                                                  .SetMessage("需要访问应用使用情况的权限,否则无法使用")
                                                  .SetPositiveButton("好的", new EventHandler <DialogClickEventArgs>((sender, e) =>
                {
                    Intent intent = new Intent(Settings.ActionUsageAccessSettings);
                    StartActivityForResult(intent, PackageUsageStatsId);
                }))
                                                  .SetNegativeButton("不给", new EventHandler <DialogClickEventArgs>((sender, e) =>
                {
                    Finish();
                }))
                                                  .SetCancelable(false).Create();
                alertDialog.Show();
            }
        }
Ejemplo n.º 3
0
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent intent)
        {
            base.OnActivityResult(requestCode, resultCode, intent);

            if (requestCode == PickImageId)
            {
                if ((resultCode == Result.Ok) && (intent != null))
                {
                    Android.Net.Uri uri    = intent.Data;
                    Stream          stream = ContentResolver.OpenInputStream(uri);

                    // Set the Stream as the completion of the Task
                    PickImageTaskCompletionSource.SetResult(stream);
                }
                else
                {
                    PickImageTaskCompletionSource.SetResult(null);
                }
            }
            else if (requestCode == PackageUsageStatsId)
            {
                AppOpsManager appOps = (AppOpsManager)GetSystemService(AppOpsService);
                int           mode   = (int)appOps.CheckOpNoThrow("android:get_usage_stats", Process.MyUid(), PackageName);
                if (mode == (int)AppOpsManagerMode.Allowed)
                {
                    Toast.MakeText(Android.App.Application.Context, "权限已获取,可以正常使用了!", ToastLength.Long).Show();
                }
                else
                {
                    AlertDialog.Builder builder     = new AlertDialog.Builder(this);
                    AlertDialog         alertDialog = builder.SetTitle("尚未给予权限")
                                                      .SetMessage("需要访问应用使用情况的权限,否则无法使用")
                                                      .SetPositiveButton("好的", new EventHandler <DialogClickEventArgs>((sender, e) =>
                    {
                        Intent intent = new Intent(Settings.ActionUsageAccessSettings);
                        StartActivityForResult(intent, PackageUsageStatsId);
                    }))
                                                      .SetNegativeButton("不给", new EventHandler <DialogClickEventArgs>((sender, e) =>
                    {
                        Finish();
                    })).Create();
                    alertDialog.Show();
                }
            }
        }
Ejemplo n.º 4
0
        //private class AppOpsCallback : Java.Lang.Object, AppOpsManager.IOnOpChangedListener
        //{
        //	public void OnOpChanged(string op, string packageName)
        //	{
        //		if (op == AppOpsManager.OpstrGetUsageStats && _cancellationTokenSource != null)
        //		{
        //			_cancellationTokenSource.Cancel();
        //		}
        //	}
        //}

        public async Task CheckPermission()
        {
            AppOpsManager appOps = (AppOpsManager)Application.Context.GetSystemService(global::Android.Content.Context.AppOpsService);

            //AppOpsCallback callback = new AppOpsCallback();
            //appOps.StartWatchingMode(AppOpsManager.OpstrGetUsageStats, Application.Context.PackageName, new AppOpsCallback());

            if (appOps.CheckOpNoThrow(AppOpsManager.OpstrGetUsageStats, Process.MyUid(), Application.Context.PackageName) != AppOpsManagerMode.Allowed)
            //while (appOps.CheckOpNoThrow(AppOpsManager.OpstrGetUsageStats, Process.MyUid(), Application.Context.PackageName) != AppOpsManagerMode.Allowed)
            {
                bool continueStarting = await SensusContext.Current.MainThreadSynchronizer.ExecuteThreadSafe(async() =>
                {
                    return(await XamarinApplication.Current.MainPage.DisplayAlert("Permission Request", "Please enable the App Usage permission for Sensus", "OK", "Cancel"));
                });


                //Check permission the second time to mitigate the case in which the permisions are asked twice. this happens if both ApplicationUdageEvent and ApplicationUsageStats probes are enabled
                if (appOps.CheckOpNoThrow(AppOpsManager.OpstrGetUsageStats, Process.MyUid(), Application.Context.PackageName) != AppOpsManagerMode.Allowed)
                {
                    if (continueStarting)
                    {
                        Intent appUsageSettings = new Intent(Settings.ActionUsageAccessSettings);
                        appUsageSettings.AddFlags(ActivityFlags.NewTask);
                        Application.Context.StartActivity(appUsageSettings);

                        //AndroidSensusServiceHelper serviceHelper = SensusServiceHelper.Get() as AndroidSensusServiceHelper;

                        //_cancellationTokenSource = new CancellationTokenSource();

                        //serviceHelper.WaitForFocus(_cancellationTokenSource.Token);

                        //_cancellationTokenSource.Dispose();
                        //_cancellationTokenSource = null;
                    }
                    else
                    {
                        _probe.Protocol.CancelStart();

                        return;
                    }
                }
            }

            //appOps.StopWatchingMode(callback);
        }
Ejemplo n.º 5
0
        public static bool IsNotificationEnabled(global::Android.Content.Context context)
        {
            AppOpsManager   mAppOps = (AppOpsManager)context.GetSystemService(global::Android.Content.Context.AppOpsService);
            ApplicationInfo appInfo = context.ApplicationInfo;
            String          pkg     = context.ApplicationContext.PackageName;
            int             uid     = appInfo.Uid;

            try
            {
                var appOpsClass             = Java.Lang.Class.ForName("android.app.AppOpsManager");
                var checkOpNoThrowMethod    = appOpsClass.GetMethod(CHECK_OP_NO_THROW, Java.Lang.Integer.Type, Java.Lang.Integer.Type, new Java.Lang.String().Class);
                var opPostNotificationValue = appOpsClass.GetDeclaredField(OP_POST_NOTIFICATION);
                var value = (int)opPostNotificationValue.GetInt(Java.Lang.Integer.Type);
                var mode  = (int)checkOpNoThrowMethod.Invoke(mAppOps, value, uid, pkg);
                return(mode == (int)AppOpsManagerMode.Allowed);
            }
            catch (Exception ex)
            {
                Log.Information(ex.Message);
            }
            return(false);
        }
    public bool GetApplicationNotificationSettings()
    {
        var context = Android.App.Application.Context;

        if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Kitkat)
        {
            return(NotificationManagerCompat.From(context).AreNotificationsEnabled());
        }
        else
        {
            AppOpsManager   mAppOps         = (AppOpsManager)context.GetSystemService(Android.Content.Context.AppOpsService);
            ApplicationInfo applicationInfo = context.ApplicationInfo;
            string          packageName     = context.ApplicationContext.PackageName;
            int             uId             = applicationInfo.Uid;

            var appOpsClass              = Class.ForName("android.app.AppOpsManager");
            var checkOpNoThrowMethod     = appOpsClass.GetMethod("checkOpNoThrow", Java.Lang.Integer.Type, Java.Lang.Integer.Type, new Java.Lang.String().Class);
            var opsPostNotificationValue = appOpsClass.GetDeclaredField("OP_POST_NOTIFICATION");
            var value = (int)opsPostNotificationValue.GetInt(Java.Lang.Integer.Type);
            var mode  = (int)checkOpNoThrowMethod.Invoke(mAppOps, value, uId, packageName);
            return(mode == (int)AppOpsManagerMode.Allowed);
        }
    }
Ejemplo n.º 7
0
        public List <AppProcess> GetAppProcessesByTime(string time = "year")
        {
            try {
                #region AppStatistics
                PackageManager packageManager = context.PackageManager;
                AppOpsManager  appOps         = (AppOpsManager)context.GetSystemService(Context.AppOpsService);

                var mode = appOps.CheckOpNoThrow(AppOpsManager.OpstrGetUsageStats, Android.OS.Process.MyUid(), context.PackageName);

                if (mode == AppOpsManager.ModeAllowed)
                {
                    UsageStatsManager mUsageStatsManager = (UsageStatsManager)context.GetSystemService(Context.UsageStatsService);

                    NetworkStatsManager networkStatsManager = (NetworkStatsManager)context.GetSystemService(Context.NetworkStatsService);

                    Calendar calendar  = Calendar.Instance;
                    long     endMillis = calendar.TimeInMillis;
                    long     startMillis;
                    if (time == "day")
                    {
                        calendar.Add(Calendar.DayOfWeekInMonth, -1);
                    }
                    else if (time == "month")
                    {
                        calendar.Add(Calendar.Month, -1);
                    }
                    else if (time == "week")
                    {
                        calendar.Add(Calendar.WeekOfMonth, -1);
                    }
                    else
                    {
                        calendar.Add(Calendar.Year, -1);
                    }
                    startMillis = calendar.TimeInMillis;

                    IDictionary <String, UsageStats> lUsageStatsMap = mUsageStatsManager.QueryAndAggregateUsageStats(startMillis, endMillis);

                    foreach (var usageStats in lUsageStatsMap)
                    {
                        long     totalTimeInMillis  = 0;
                        long     totalTimeInSeconds = 0;
                        string   packageName        = "";
                        string   appName            = "";
                        long     receivedWifi       = 0;
                        long     sentWifi           = 0;
                        long     receivedMobile     = 0;
                        long     sentMobile         = 0;
                        DateTime lastUsage          = new DateTime();

                        packageName        = usageStats.Key;
                        totalTimeInMillis  = usageStats.Value.TotalTimeInForeground;
                        totalTimeInSeconds = totalTimeInMillis / 1000 / 60;
                        appName            = AppNameByPackageName(packageName);

                        ApplicationInfo info = packageManager.GetApplicationInfo(packageName, 0);
                        if (info != null)
                        {
                            int          uid = info.Uid;
                            NetworkStats networkStatsWifi = networkStatsManager.QueryDetailsForUid(ConnectivityType.Wifi, null, startMillis, endMillis, uid);

                            NetworkStats.Bucket bucketWifi = new NetworkStats.Bucket();
                            while (networkStatsWifi.HasNextBucket)
                            {
                                networkStatsWifi.GetNextBucket(bucketWifi);
                                receivedWifi += bucketWifi.RxBytes;
                                sentWifi     += bucketWifi.TxBytes;
                            }
                            NetworkStats        networkStatsMobile = networkStatsManager.QueryDetailsForUid(ConnectivityType.Mobile, null, startMillis, endMillis, uid);
                            NetworkStats.Bucket bucketMobile       = new NetworkStats.Bucket();
                            while (networkStatsMobile.HasNextBucket)
                            {
                                networkStatsMobile.GetNextBucket(bucketMobile);
                                receivedMobile += bucketMobile.RxBytes;
                                sentMobile     += bucketMobile.TxBytes;
                            }
                        }

                        appProcesses.Add(new AppProcess {
                            PackageName = packageName, TimeOfAppUsageInSeconds = totalTimeInSeconds, AppName = appName, NetworkUsageTotal = receivedWifi + sentWifi + receivedMobile + sentMobile, NetworkUsageSend = sentWifi + sentMobile, NetworkUsageReceived = receivedWifi + receivedMobile
                        });
                    }
                }
                else
                {
                    // When needed permission
                    var activity = (MainActivity)Forms.Context;
                    activity.StartActivityForResult(new Intent(Settings.ActionUsageAccessSettings), MY_PERMISSIONS_REQUEST_PACKAGE_USAGE_STATS);
                }
            } catch (Exception ex) {
                throw new Exception(ex.Message);
            }
            #endregion
            return(appProcesses);
        }