public AndroidSensusServiceHelper()
 {
     _actionsToRunUsingMainActivity = new List <Action <AndroidMainActivity> >();
     _userDeniedBluetoothEnable     = false;
     _wakeLock = (Application.Context.GetSystemService(global::Android.Content.Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
     _deviceId = Settings.Secure.GetString(Application.Context.ContentResolver, Settings.Secure.AndroidId);
 }
 protected override void OnDestroy()
 {
     base.OnDestroy();
     wakeLock.Release();
     wakeLock = null;
     Log.Info(TAG, " wakelock wakeLock.Release(); ");
 }
Example #3
0
 public AndroidDeviceSettings(AndroidApp app) : base(app)
 {
     _activity     = app.MainActivity;
     _powerManager = _activity.GetSystemService(Context.PowerService) as PowerManager;
     _wifiManager  = _activity.GetSystemService(Context.WifiService) as WifiManager;
     _wakeLock     = _powerManager.NewWakeLock(WakeLockFlags.Full, "DSAMobile");
 }
        /// <summary>
        /// Finish the execution from previous <see cref="StartWakefulService(Context, Intent)"/>.
        /// </summary>
        /// <remarks>
        /// Any wake lock that was being held will now be released.
        /// </remarks>
        /// <param name="intent">The <see cref="Intent"/> that was originally generated by <see cref="StartWakefulService(Context, Intent)"/></param>
        /// <returns><c>true</c> if the intent is associated with a wake lock that is now released.
        /// Returns <c>false</c> if there was no wake lock specified for it.</returns>
        internal static bool CompleteWakefulIntent(Intent intent)
        {
            int id = intent.GetIntExtra(ExtraWakeLockId, 0);

            if (id == 0)
            {
                return(false);
            }

            lock (activeWakeLocksMutex) {
                PowerManager.WakeLock wl = activeWakeLocks[id];
                if (wl != null)
                {
                    wl.Release();
                    activeWakeLocks.Remove(id);

                    return(true);
                }

                // We return true whether or not we actually found the wake lock
                // the return code is defined to indicate whether the Intent contained
                // an identifier for a wake lock that it was supposed to match.
                // We just log a warning here if there is no wake lock found, which could
                // happen for example if this function is called twice on the same
                // intent or the process is killed and restarted before processing the intent.
                Android.Util.Log.Warn("ParseWakefulHelper", "No active wake lock id #" + id);
                return(true);
            }
        }
Example #5
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(Window.FEATURE_NO_TITLE);
            GetWindow().SetFlags(IWindowManager_LayoutParams.FLAG_FULLSCREEN,
                                 IWindowManager_LayoutParams.FLAG_FULLSCREEN);

            bool isPortrait = GetResources().GetConfiguration().Orientation == Configuration.ORIENTATION_PORTRAIT;
            int frameBufferWidth = isPortrait ? 480 : 800;
            int frameBufferHeight = isPortrait ? 800 : 480;
            Bitmap frameBuffer = Bitmap.CreateBitmap(frameBufferWidth,
                                                     frameBufferHeight, Bitmap.Config.RGB_565);

            float scaleX = (float)frameBufferWidth
                           / GetWindowManager().GetDefaultDisplay().GetWidth();
            float scaleY = (float)frameBufferHeight
                           / GetWindowManager().GetDefaultDisplay().GetHeight();

            renderView = new AndroidFastRenderView(this, frameBuffer);
            graphics = new AndroidGraphics(GetAssets(), GetAssetsPrefix(), frameBuffer);
            fileIO = new AndroidFileIO(this);
            audio = new AndroidAudio(this);
            input = new AndroidInput(this, renderView, scaleX, scaleY);
            screen = getInitScreen();
            SetContentView(renderView);

            PowerManager powerManager = (PowerManager)GetSystemService(Context.POWER_SERVICE);
            wakeLock = powerManager.NewWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
        }
        /// <summary>
        /// Do a <see cref="Context.StartService(Intent)"/>, but holding a wake lock while the service starts.
        /// </summary>
        /// <remarks>
        /// This will modify the intent to hold an extra identifying the wake lock. When the service receives it
        /// in <see cref="Service.OnStartCommand"/>, it should pass back the <see cref="Intent"/> it receives there to
        /// <see cref="CompleteWakefulIntent(Intent)"/> in order to release the wake lock.
        /// </remarks>
        /// <param name="context">The <see cref="Context"/> in which it operate.</param>
        /// <param name="intent">The <see cref="Intent"/> with which to start the service, as per <see cref="Context.StartService(Intent)"/>.</param>
        /// <returns>The <see cref="ComponentName"/> of the <see cref="Service"/> being started.</returns>
        internal static ComponentName StartWakefulService(Context context, Intent intent)
        {
            lock (activeWakeLocksMutex) {
                int id = nextId;
                nextId++;
                if (nextId <= 0)
                {
                    nextId = 1;
                }

                intent.PutExtra(ExtraWakeLockId, id);
                ComponentName comp = context.StartService(intent);
                if (comp == null)
                {
                    return(null);
                }

                PowerManager          pm = PowerManager.FromContext(context);
                PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "wake: " + comp.FlattenToShortString());
                wl.SetReferenceCounted(false);
                wl.Acquire(WakeLockTimeout);
                activeWakeLocks[id] = wl;

                return(comp);
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            OS.AutoDisposedGL = false;

            // Screen orientation
            var requiredOrientation = (desc.Orientation == ApplicationOrientations.Landscape) ? Android.Content.PM.ScreenOrientation.Landscape : Android.Content.PM.ScreenOrientation.Portrait;

            RequestedOrientation = requiredOrientation;

            // Remove title bar
            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);

            // Create gl view
            VolumeControlStream = Android.Media.Stream.Music;
            view = new GLView(this);
            SetContentView(view);

            // Ads
            if (desc.UseAds)
            {
                adMobView = AdMobWrapper.CreateAdView(this, desc.PublisherID);
                var layout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WrapContent, FrameLayout.LayoutParams.WrapContent, GravityFlags.Bottom);
                AddContentView(adMobView, layout);
                AdMobWrapper.LoadAd(adMobView, false);
                adMobView.Visibility = Android.Views.ViewStates.Visible;
                adMobView.BringToFront();
            }

            // keep screen from locking
            var power = (PowerManager)GetSystemService(Context.PowerService);

            wakeLock = power.NewWakeLock(WakeLockFlags.ScreenDim, "AndroidApplication");
        }
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            Task.Run(() => {
                try
                {
                    PowerManager pm          = (PowerManager)GetSystemService(Context.PowerService);
                    PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "My Tag");
                    wl.Acquire();
                    var counter = new TimerTask();
                    counter.RunTimer(_cts, startId).Wait();
                }
                catch (Exception ex)
                {
                }
                finally
                {
                    if (_cts.IsCancellationRequested)
                    {
                        var message = new CancelledMessage();
                        //Device.BeginInvokeOnMainThread(
                        //    () => MessagingCenter.Send(message, "CancelledMessage")
                        //);
                    }
                }
            }, _cts.Token);

            return(StartCommandResult.Sticky);
        }
Example #9
0
        private async Task StartInBackground()
        {
            try
            {
                _backgroundService = _backgroundServiceCreationFunc();
                await _backgroundService.StartAsync();

                using (var powerService = ApplicationContext.GetSystemService(PowerService) as PowerManager)
                {
                    if (powerService == null)
                    {
                        return;
                    }
                    _wakeLock = powerService.NewWakeLock(WakeLockFlags.Partial, _serviceName);
                }

                AcquireWakelock();
                if (_hasPeriodicTask)
                {
                    StartHandlerThread();
                }
            }
            catch (Exception e)
            {
                Android.Util.Log.Error(_serviceName, e.ToString());
            }
        }
Example #10
0
    public bool ReleaseLock(string lock_type = "screenDim")
    {
        lock (wakeLocks)
        {
            if (!wakeLocks.ContainsKey(lock_type))
            {
                return(false);
            }

            switch (lock_type)
            {
            case "screenDim":
            case "partial":
            case "proximityScreenOff":
                PowerManager.WakeLock pm_lock = (PowerManager.WakeLock)wakeLocks[lock_type];
                pm_lock.Release();
                break;

            case "wifi":
                WifiManager.WifiLock wm_lock = (WifiManager.WifiLock)wakeLocks[lock_type];
                wm_lock.Release();
                break;
            }
            wakeLocks.Remove(lock_type);
            return(true);
        }
    }
        public ScreenLockImplementation()
        {
            var ctx = Forms.Context;             // useful for many Android SDK features

            _pm = (PowerManager)ctx.GetSystemService(Android.Content.Context.PowerService);
            _wl = _pm.NewWakeLock(WakeLockFlags.Full, "Stay on");
        }
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {
            if (intent.Action.Equals(MainValues.ACTION_START_SERVICE))
            {
                Notification notification;
                if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                {
                    CreateNotificationChannel();
                    notification = CreateNotificationWithChannelId();
                }
                else
                {
                    notification = CreateNotification();
                }

                StartForeground(MainValues.SERVICE_RUNNING_NOTIFICATION_ID, notification);
            }
            //else if (intent.Action.Equals(Constants.ACTION_STOP_SERVICE))
            //    _hiddenCamera.Stop();
            PowerManager pm = (PowerManager)GetSystemService(PowerService);

            PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.Partial, "THT");
            wl.Acquire();
            //test();
            return(StartCommandResult.Sticky);
        }
Example #13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            PowerManager pm = (PowerManager)GetSystemService(Context.PowerService);

            PowerManager.WakeLock wl = pm.NewWakeLock(WakeLockFlags.ScreenBright, "My Tag");
            wl.Acquire();
            this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            text      = FindViewById <EditText>(Resource.Id.editText1);
            text.Text = getIP();
            t1        = FindViewById <TextView>(Resource.Id.textView2);
            t2        = FindViewById <TextView>(Resource.Id.textView3);

            var client = new TcpClient();

            Button button1 = FindViewById <Button>(Resource.Id.button1);

            button1.Click += StartBotClicked;

            Button button2 = FindViewById <Button>(Resource.Id.button2);

            button2.Click += NetworkTestClicked;

            usbManager = GetSystemService(Context.UsbService) as UsbManager;

            image             = FindViewById <TextureView>(Resource.Id.imageView1);
            mc                = new MyCamera(image);
            mc.FrameRefreshed = sendFrame;
        }
Example #14
0
        public void LoadTimerSensor()
        {
            View viewAlert = View.Inflate(this, Resource.Layout.LayoutTimerSensor, null);

            AlertDialog.Builder Message = new AlertDialog.Builder(this);
            Message.SetTitle("زمان را برحسب دقیقه انتخاب کنید"); Message.SetView(viewAlert);
            Message.SetIcon(Resource.Drawable.Timer);
            NumberPicker np = (NumberPicker)viewAlert.FindViewById(Resource.Id.LTimerSensorNumberPickerTS);

            np.MaxValue = 25; np.MinValue = 1;
            np.SetOnClickListener(this);
            Message.SetPositiveButton("فعال کن", delegate
            {
                ValueTS = (np.Value * 60) * 10;
                TimerSensor.Start();
                Toast.MakeText(this, np.Value + " M " + "تایمر سنسور فعال شد", ToastLength.Short).Show();
                WLock = dfpowermanager.NewWakeLock(WakeLockFlags.Full, "DoNotSleep");
                WLock.Acquire();
            });
            Message.SetNegativeButton("لغو", delegate { });
            Message.SetNeutralButton("لغو تایمر", delegate
            {
                TimerSensor.Stop(); ValueTS = 0;
                Toast.MakeText(this, "تایمر سنسور غیر فعال شد", ToastLength.Short).Show();
                try
                {
                    WLock.Release();
                }
                catch { }
            });
            Message.Create(); Message.Show();
        }
Example #15
0
        public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
        {
            switch (intent?.Action)
            {
            case ActionPlay: Play(); break;

            case ActionStop: Stop(); break;

            case ActionPause: Pause(); break;

            case ActionNext: SkipToNext(null); break;

            case ActionPrevious: SkipToPrev(); break;

            case ActionLoadUrl: LoadVideoFromUrl(intent); break;

            case ActionBkgrdNote: ToggleNotificationShouldPlayInBkgrd(true); break;

            case ActionResumeNote: ToggleNotificationShouldPlayInBkgrd(false); break;
            }

            try{ WifiManager = (WifiManager)GetSystemService(Context.WifiService); }
            catch {  }
            ExtStickyServ = this;
            try
            {
                Pm = (PowerManager)GetSystemService(Context.PowerService);
                PowerManager.WakeLock _wl = Pm.NewWakeLock(WakeLockFlags.Partial, "BitChute Wakelock");
                _wl.Acquire();
            }
            catch (Exception ex) { Console.WriteLine(ex.Message); }
            return(StartCommandResult.Sticky);
        }
Example #16
0
        public HttpTransferTasks()
        {
            this.conn = new SqliteConnection(); // this will block for a moment
            this.CurrentTasksChanged += (sender, args) =>
            {
                var powerManager = (PowerManager)Application.Context.GetSystemService(Context.PowerService);

                if (this.CurrentTasks.Count == 0)
                {
                    this.wakeLock?.Release();
                    this.wakeLock = null;
                }
                else if (this.wakeLock == null)
                {
                    this.wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "HTTPTRANSFERS");
                    this.wakeLock.Acquire();
                }
            };
            Task.Run(() =>
            {
                var cfgs    = this.conn.TaskConfigurations.ToList();
                var headers = this.conn.TaskConfigurationHeaders.ToList();

                foreach (var cfg in cfgs)
                {
                    var cheaders = headers.Where(x => x.SqlTaskConfigurationId == cfg.Id).ToList();
                    this.RebuildTask(cfg, cheaders);
                }
            });
        }
Example #17
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            RequestWindowFeature(Window.FEATURE_NO_TITLE);
            GetWindow().SetFlags(IWindowManager_LayoutParams.FLAG_FULLSCREEN,
                                 IWindowManager_LayoutParams.FLAG_FULLSCREEN);

            bool   isPortrait        = GetResources().GetConfiguration().Orientation == Configuration.ORIENTATION_PORTRAIT;
            int    frameBufferWidth  = isPortrait ? 480 : 800;
            int    frameBufferHeight = isPortrait ? 800 : 480;
            Bitmap frameBuffer       = Bitmap.CreateBitmap(frameBufferWidth,
                                                           frameBufferHeight, Bitmap.Config.RGB_565);

            float scaleX = (float)frameBufferWidth
                           / GetWindowManager().GetDefaultDisplay().GetWidth();
            float scaleY = (float)frameBufferHeight
                           / GetWindowManager().GetDefaultDisplay().GetHeight();

            renderView = new AndroidFastRenderView(this, frameBuffer);
            graphics   = new AndroidGraphics(GetAssets(), GetAssetsPrefix(), frameBuffer);
            fileIO     = new AndroidFileIO(this);
            audio      = new AndroidAudio(this);
            input      = new AndroidInput(this, renderView, scaleX, scaleY);
            screen     = getInitScreen();
            SetContentView(renderView);

            PowerManager powerManager = (PowerManager)GetSystemService(Context.POWER_SERVICE);

            wakeLock = powerManager.NewWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
        }
Example #18
0
        public override void OnDestroy()
        {
            // We need to shut things down.
            //Log.Info(Tag, "OnDestroy: The started service is shutting down.");

            // Remove the notification from the status bar.
            NotificationManagerCompat notificationManager = NotificationManagerCompat.From(this);

            notificationManager.Cancel(ServiceRunningNotificationId);

            if (_wakeLockCpu != null)
            {
                try
                {
                    _wakeLockCpu.Release();
                    _wakeLockCpu.Dispose();
                }
                catch (Exception)
                {
                    // ignored
                }
                _wakeLockCpu = null;
            }

            _activityCommon.Dispose();
            _activityCommon = null;
            _isStarted      = false;
            base.OnDestroy();
        }
Example #19
0
        public override void OnReceive(Context context, Intent intent)
        {
            try
            {
                PowerManager          pm = (PowerManager)context.GetSystemService(Context.PowerService);
                PowerManager.WakeLock w1 = pm.NewWakeLock(WakeLockFlags.Partial, "NotificationReceiver");
                w1.Acquire();

                var pendingIntent = PendingIntent.GetActivity(context, 0, new Intent(context, typeof(MainActivity)), 0);

                Notification.Builder notifBuilder = new Notification.Builder(context)
                                                    .SetContentIntent(pendingIntent)
                                                    .SetContentTitle("Skin Selfie Reminder")
                                                    .SetContentText("Remember to take a photo of your condition '" + intent.GetStringExtra("conditionName") + "'!")
                                                    .SetSmallIcon(Resource.Drawable.icon)
                                                    .SetAutoCancel(true);

                Notification        notification        = notifBuilder.Build();
                NotificationManager notificationManager =
                    context.GetSystemService(Context.NotificationService) as NotificationManager;

                notificationManager.Notify(0, notification);
                w1.Release();
            }
            catch (Exception e)
            {
                Console.WriteLine("ON RECEIVE ERR: " + e.Message);
            }
        }
Example #20
0
        protected override void OnHandleIntent(Intent intent)
        {
            lock (LOCK)
            {
                if (sWakeLock == null)
                {
                    var pm = PowerManager.FromContext(this.ApplicationContext);
                    sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, KINVEY_FCM);
                }
            }

            sWakeLock.Acquire();


            try
            {
                string action = intent.Action;

                if (action.Equals(Constants.STR_C2DM_INTENT_REGISTRATION))
                {
                    var registrationId = intent.GetStringExtra(REGISTRATION_ID);
                    onRegistered(registrationId);
                }
                else if (action.Equals(Constants.STR_KINVEY_FCM_UNREGISTRATION))
                {
                    var unregistrationId = intent.GetStringExtra(Constants.STR_UNREGISTRATION_ID);
                    onUnregistered(unregistrationId);
                }
                else if (action.Equals(Constants.STR_C2DM_INTENT_RECEIVE))
                {
                    string message = null;

                    if (intent.HasExtra(MESSAGE_FROM_KINVEY_CONSOLE))
                    {
                        message = intent.GetStringExtra(MESSAGE_FROM_KINVEY_CONSOLE);
                    }
                    else if (intent.HasExtra(MESSAGE_FROM_FCM))
                    {
                        message = intent.GetStringExtra(MESSAGE_FROM_FCM);
                    }

                    onMessage(message);
                }
                else if (action.Equals(Constants.STR_KINVEY_ANDROID_ERROR))
                {
                    onError(intent.GetStringExtra(Constants.STR_GENERAL_ERROR));
                }
            }
            finally
            {
                lock (LOCK)
                {
                    //Sanity check for null as this is a public method
                    if (sWakeLock != null)
                    {
                        sWakeLock.Release();
                    }
                }
            }
        }
Example #21
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            RequestPermission();

            _powerManager = (PowerManager)GetSystemService(PowerService);
            _wakeLock     = _powerManager.NewWakeLock(WakeLockFlags.Full, "@string/app_name");

            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.activity_main);

            Android.Support.V7.Widget.Toolbar toolbar = FindViewById <Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
            SetSupportActionBar(toolbar);

            MobileBarcodeScanner.Initialize(Application);

            WebView webView = FindViewById <WebView>(Resource.Id.webView);

            webView.SetWebChromeClient(new WebChromeClient());
            webView.SetWebViewClient(new WebViewClient());
            webView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
            webView.Settings.JavaScriptEnabled                = true;
            webView.Settings.AllowFileAccessFromFileURLs      = true;
            webView.Settings.AllowUniversalAccessFromFileURLs = true;
            webView.Settings.AllowFileAccess = true;
            webView.ClearHistory();
            webView.ClearCache(true);
            WebSettings webSettings = webView.Settings;

            webSettings.SetAppCacheEnabled(false);

            webView.AddJavascriptInterface(new QRScannerJSInterface(webView, this), "CSharpQRInterface");
            webView.LoadUrl("file:///android_asset/TestBarCode/testbarcode.html");
            //webView.LoadUrl("http://IP-YOURWEBSERVER/testbarcode.html");    //if you want to test on your web server, copy testbarcode.html on your web server
        }
Example #22
0
        /// <summary>
        /// 获取电源锁
        /// </summary>
        private void AcquireWakeLock()
        {
            if (null == _wakeLock)
            {
                using (PowerManager pm = (PowerManager)GetSystemService(Context.PowerService))
                {
                    _wakeLock = pm.NewWakeLock(WakeLockFlags.Partial | WakeLockFlags.AcquireCausesWakeup, "MyWakelockTag");
                    if (_wakeLock != null)
                    {
                        _wakeLock.Acquire();

                        //服务没运行时
                        if (!IsRun)
                        {
                            if (_mediaPlayer != null && !_mediaPlayer.IsPlaying)
                            {
                                var assembly = typeof(App).GetTypeInfo().Assembly;
                                var path     = "DCMS.Client.Resources.raw";
                                using (var _audioStream = assembly?.GetManifestResourceStream($"{path}.cactus.mp3"))
                                {
                                    if (_audioStream != null)
                                    {
                                        _mediaPlayer.Load(_audioStream);
                                        _mediaPlayer.Loop = true;
                                        _mediaPlayer.Play();
                                        IsRun = true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
Example #23
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);
            bool isLandscape = this.Resources.Configuration.Orientation == Android.Content.Res.Orientation.Landscape;

            int frameBufferWidth  = isLandscape ? 960 : 540;
            int frameBufferHeight = isLandscape ? 540 : 960;

            Bitmap frameBuffer = Bitmap.CreateBitmap(frameBufferWidth, frameBufferHeight, Bitmap.Config.Rgb565);

            float scaleX = (float)frameBufferWidth / this.WindowManager.DefaultDisplay.Width;
            float scaleY = (float)frameBufferHeight / this.WindowManager.DefaultDisplay.Height;

            _renderView = new AndroidFastRenderView(this, frameBuffer);
            _graphics   = new AndroidGraphics(Assets, frameBuffer);
            _fileIO     = new AndroidFileIO(Assets);
            _audio      = new AndroidAudio(this);
            _input      = new AndroidInput(this, _renderView, scaleX, scaleY);
            _screen     = GetStartScreen();
            SetContentView(_renderView);

            PowerManager pw = (PowerManager)GetSystemService(Context.PowerService);

            _wl = pw.NewWakeLock(WakeLockFlags.Full, "GLGame");
            // Create your application here
        }
Example #24
0
 public override void OnReceive(Context context, Intent intent)
 {
     if (Build.VERSION.SdkInt >= BuildVersionCodes.M)
     {
         PowerManager          pm       = (PowerManager)context.GetSystemService("power");
         PowerManager.WakeLock wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "LocationManagerService");
         if (pm.IsDeviceIdleMode)
         {
             // the device is now in doze mode
             Vibrator vibrator = (Vibrator)context.GetSystemService("vibrator");
             vibrator.Vibrate(100);
             if (wakeLock.IsHeld == false)
             {
                 wakeLock.Acquire();
             }
         }
         else
         {
             Vibrator vibrator = (Vibrator)context.GetSystemService("vibrator");
             vibrator.Vibrate(1000);
             if (wakeLock.IsHeld)
             {
                 wakeLock.Release();
             }
             // the device just woke up from doze mode
         }
     }
 }
Example #25
0
 public void SetService(AndroidSensusService service)
 {
     _service             = service;
     _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
     _deviceId            = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);
     _textToSpeech        = new AndroidTextToSpeech(_service);
     _wakeLock            = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
 }
        public override void OnReceive(Context context, Intent intent)
        {
            var pm = (PowerManager)context.GetSystemService(Context.PowerService);

            PowerManager.WakeLock wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "BackgroundReceiver");

            wakeLock.Release();
        }
Example #27
0
        public BluetoothWakeLock()
        {
            PowerManager pm = (PowerManager)Application.Context.GetSystemService(Context.PowerService);

            Tag += Guid.NewGuid().ToString();
            WakeLockInternal = pm.NewWakeLock(WakeLockFlags.Partial | WakeLockFlags.LocationModeNoChange, Tag);
            WakeLockInternal.Acquire();
        }
Example #28
0
 // スリープを有効にする
 public void EnableSleep()
 {
     if (_wakeLock != null)
     {
         _wakeLock.Release();
         _wakeLock = null;
     }
 }
Example #29
0
        public KeepAwakeLock()
        {
            PowerManager pm = (PowerManager)Application.Context.GetSystemService(Context.PowerService);

            Tag += Guid.NewGuid().ToString();
            WakeLockInternal = pm.NewWakeLock(WakeLockFlags.Full, Tag);
            WakeLockInternal.Acquire();
        }
Example #30
0
 private void CheckWakeLock(WakeLockFlags flags)
 {
     if (mWakeLock == null)
     {
         CancelKeepingAwake();
         mWakeLock = GetSystemService <PowerManager>(Context.PowerService).NewWakeLock(flags, Class.FromType(typeof(Device)).Name);
     }
 }
Example #31
0
        protected override void OnResume()
        {
            base.OnResume();
            var powerManager = (PowerManager)this.GetSystemService(Context.PowerService);

            wakeLock = powerManager.NewWakeLock(WakeLockFlags.Full, "My Lock");
            wakeLock.Acquire();
        }
		private static PowerManager.WakeLock GetLock(Context context)
		{
			if (lockStatic == null)
			{
				PowerManager mgr = (PowerManager)context.GetSystemService(Context.PowerService);
				lockStatic = mgr.NewWakeLock(WakeLockFlags.Partial, LOCK_NAME_STATIC);
				lockStatic.SetReferenceCounted(true);
			}
			return (lockStatic);
		}
Example #33
0
        static void RunIntentInService(Context context, Intent intent)
        {
            lock (LOCK)
            {
                if (wakeLock == null)
                {
                    var pm = PowerManager.FromContext(context);
                    wakeLock = pm.NewWakeLock(WakeLockFlags.Partial, "Woken lock");
                }
            }

            wakeLock.Acquire();
            intent.SetClass(context, typeof(GPSDroidService));
            context.StartService(intent);
        }
Example #34
0
        public static void RunIntentInService(Context context, Intent intent)
        {
            lock (LOCK)
            {
                if (sWakeLock == null)
                {
                    // This is called from BroadcastReceiver, there is no init.
                    var pm = PowerManager.FromContext(context);
                    sWakeLock = pm.NewWakeLock(
                    WakeLockFlags.Partial, "My WakeLock Tag");
                }
            }

            sWakeLock.Acquire();
            intent.SetClass(context, typeof(GCMIntentService));
            context.StartService(intent);
        }
		internal static void RunIntentInService(Context context, Intent intent)
		{
			lock (_lock)
			{
				if (_wakeLock == null)
				{
					// This is called from BroadcastReceiver, there is no init.
					var pm = PowerManager.FromContext(context);
					_wakeLock = pm.NewWakeLock(
						WakeLockFlags.Partial, "Donky GCM Wakelock");
				}
			}

			_wakeLock.Acquire();
			intent.SetClass(context, typeof(DonkyGcmIntentService));
			context.StartService(intent);
		}
Example #36
0
        internal static void RunIntentInService(Context context, Intent intent, Type classType)
        {
            lock (LOCK)
            {
                if (sWakeLock == null)
                {
                    // This is called from BroadcastReceiver, there is no init.
                    var pm = PowerManager.FromContext(context);
                    sWakeLock = pm.NewWakeLock(WakeLockFlags.Partial, WAKELOCK_KEY);
                }
            }

            Log.Verbose(TAG, "Acquiring wakelock");
            sWakeLock.Acquire();
            //intent.SetClassName(context, className);
            intent.SetClass(context, classType);

            context.StartService(intent);
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // full screen & full brightness
            this.RequestWindowFeature(WindowFeatures.NoTitle);
            Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);
            Window.SetFlags(WindowManagerFlags.KeepScreenOn, WindowManagerFlags.KeepScreenOn);
            mWL = ((PowerManager)GetSystemService(Context.PowerService)).NewWakeLock(WakeLockFlags.Full, "BOB");
            mWL.Acquire();
            mView = new MainView(this);
            SetContentView(mView);
            LinearLayout ll = new LinearLayout(this);
            Button b = new Button(this);
            b.SetText("Hello", TextView.BufferType.Normal);
            ll.AddView(b);
            ll.SetGravity(GravityFlags.CenterHorizontal | GravityFlags.CenterVertical);
            this.AddContentView(ll,
                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, LinearLayout.LayoutParams.MatchParent));
        }
        /// <summary>
        /// Called when the activity is first created. </summary>
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Get an instance of the SensorManager
            mSensorManager = (SensorManager)GetSystemService(SENSOR_SERVICE);

            // Get an instance of the PowerManager
            mPowerManager = (PowerManager)GetSystemService(POWER_SERVICE);

            // Get an instance of the WindowManager
            mWindowManager = (IWindowManager)GetSystemService(WINDOW_SERVICE);
            mDisplay = mWindowManager.GetDefaultDisplay();

            // Create a bright wake lock
            mWakeLock = mPowerManager.NewWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, this.GetType().Name);

            // instantiate our simulation view and set it as the activity's content
            mSimulationView = new SimulationView(this);
            SetContentView(mSimulationView);
        }
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            SetContentView(Resource.Layout.main);

            SetupViews();

            _batteryReceiver = new BatteryReceiver(_batteryTemp, _batteryLevel, _batteryHealth, _batteryVoltage);
            _powerManager = (PowerManager) GetSystemService(PowerService);
            _wakeLock = _powerManager.NewWakeLock(WakeLockFlags.Full, "BatteryDrainer");

            _startStopButton.Click += (s, e) =>
            {
                if (_startStopButton.Checked) //on
                {
                    Start();
                }
                else //off
                {
                    Stop();
                }
            };
        }
Example #40
0
        protected override void OnDestroy()
        {
            base.OnDestroy();
            try
            {
                StopTimer();
                StopDataManager();
                if (cameraManager != null)
                {
                    cameraManager.Error -= HandleError;
                    cameraManager.PictureTaken -= CameraManager_PictureTaken;
                    cameraManager.Close();
                    cameraManager.Dispose();
                    cameraManager = null;
                }

                if (wakeLock != null)
                {
                    wakeLock.Release();
                    wakeLock.Dispose();
                    wakeLock = null;
                }

                if (locTrackerGPS != null)
                {
                    locTrackerGPS.Dispose();
                }

                if (locTrackerNetwork != null)
                {
                    locTrackerNetwork.Dispose();
                }
            }
            catch (Exception e)
            {
                showError(e);
            }
        }
 public void SetService(AndroidSensusService service)
 {
     _service = service;
     _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
     _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
     _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);
     _textToSpeech = new AndroidTextToSpeech(_service);
     _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
 }
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate (savedInstanceState);
            OS.AutoDisposedGL = false;

            // Screen orientation
            var requiredOrientation = (desc.Orientation == ApplicationOrientations.Landscape) ? Android.Content.PM.ScreenOrientation.Landscape : Android.Content.PM.ScreenOrientation.Portrait;
            RequestedOrientation = requiredOrientation;

            // Remove title bar
            RequestWindowFeature(WindowFeatures.NoTitle);
            Window.SetFlags(WindowManagerFlags.Fullscreen, WindowManagerFlags.Fullscreen);

            // Create gl view
            VolumeControlStream = Android.Media.Stream.Music;
            view = new GLView(this);
            SetContentView(view);

            // Ads
            if (desc.UseAds)
            {
                adMobView = AdMobWrapper.CreateAdView(this, desc.PublisherID);
                var layout = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WrapContent, FrameLayout.LayoutParams.WrapContent, GravityFlags.Bottom);
                AddContentView(adMobView, layout);
                AdMobWrapper.LoadAd(adMobView, false);
                adMobView.Visibility = Android.Views.ViewStates.Visible;
                adMobView.BringToFront();
            }

            // keep screen from locking
            var power = (PowerManager)GetSystemService(Context.PowerService);
            wakeLock = power.NewWakeLock(WakeLockFlags.ScreenDim, "AndroidApplication");
        }
Example #43
0
        /// <summary>
        /// 起動時
        /// </summary>
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // 画面の向きを固定する
            RequestedOrientation = Android.Content.PM.ScreenOrientation.Landscape;

            // 各種フラグ設定
            this.Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            //ウェイクロック
            using (PowerManager pm = (PowerManager)GetSystemService(Service.PowerService))
            {
                wakeLock = pm.NewWakeLock(WakeLockFlags.ScreenDim, PackageName);
                wakeLock.Acquire();
            }

            //設定読み込み
            settings = Settings.Load(this);

            //カメラを開く
            cameraManager = new CameraManager();
            cameraManager.PictureTaken += CameraManager_PictureTaken;
            cameraManager.Open();

            // カメラ表示設定
            cameraSurfaceView = FindViewById<SurfaceView>(Resource.Id.surfaceView1);
            cameraSurfaceView.Holder.AddCallback(this);
            cameraSurfaceView.Holder.SetType(SurfaceType.PushBuffers);

            //位置情報を開く
            locTrackerGPS = new LocationTracker(this, LocationManager.GpsProvider);
            locTrackerGPS.Start();
            locTrackerNetwork = new LocationTracker(this, LocationManager.NetworkProvider);
            locTrackerNetwork.Start();

            // 各種イベントを登録する
            SetupEvents();
        }
 protected override void OnStart()
 {
     base.OnStart();
     // Keep screen and wifi awake
     var powerManager = (PowerManager)GetSystemService(PowerService);
     var wifiManager = (WifiManager)GetSystemService(WifiService);
     _wakeLock = powerManager.NewWakeLock(WakeLockFlags.Full, "no sleep");
     _wakeLock.Acquire();
     _wifiLock = wifiManager.CreateWifiLock(WifiMode.FullHighPerf, "wifi on");
     _wifiLock.Acquire();
 }
 private void AcquireWakeLock()
 {
     if (null != _wakeLock) return;
     PowerManager powerManager = ApplicationContext.GetSystemService(Context.PowerService) as PowerManager;
     if (powerManager != null)
         _wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial | WakeLockFlags.OnAfterRelease,
             ActionMoblieLocatorService);
     //if (null != _wakeLock)
     //{
     //    _wakeLock.Acquire();
     //}
     _wakeLock?.Acquire();
 }
Example #46
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            powerManager = (PowerManager)GetSystemService(Context.PowerService);
            wakeLock = powerManager.NewWakeLock(WakeLockFlags.Partial, "MyWakeLock");
            wakeLock.Acquire();

            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.Pedometer);

            chrono = FindViewById<Chronometer>(Resource.Id.chronometer1);
            sensorManager = (SensorManager)GetSystemService(Context.SensorService);
            stepsTextView = FindViewById<TextView>(Resource.Id.pedometer);
            caloriesTextView = FindViewById<TextView>(Resource.Id.calories);
            speedTextView = FindViewById<TextView>(Resource.Id.speed);
            distanceTextView = FindViewById<TextView>(Resource.Id.distance);
            timeTextView = FindViewById<TextView>(Resource.Id.time);

            if (savedInstanceState != null)
            {
                steps = savedInstanceState.GetInt("steps", 0);
                calories = savedInstanceState.GetFloat("calories", 0.0f);
                speed = savedInstanceState.GetFloat("speed", 0.0f);
                distance = savedInstanceState.GetFloat("distance", 0.0f);
                chrono.Base = savedInstanceState.GetLong("time", SystemClock.ElapsedRealtime());
                run = savedInstanceState.GetBoolean("run", false);
            }

            chrono.Format = "00:0%s";
            chrono.OnChronometerTickListener = this;

            int h = 480;
            mYOffset = h * 0.5f;
            mScale[0] = -(h * 0.5f * (1.0f / (SensorManager.StandardGravity * 2)));
            mScale[1] = -(h * 0.5f * (1.0f / (SensorManager.MagneticFieldEarthMax)));

            if (run)
            {
                refreshTextViews();
                sensorsListenerRegister();
                chrono.Start();
            }
        }
Example #47
0
		private void ToggleKeepScreenOn(bool flag)
		{
			if (flag)
			{
				var powerManager = (PowerManager) GetSystemService(PowerService);
				_wakeLock = powerManager.NewWakeLock(WakeLockFlags.ScreenBright, Tag);
				_wakeLock.Acquire();
				return;
			}
			try
			{
				if (_wakeLock != null) _wakeLock.Release();
			}
			catch (Java.Lang.RuntimeException e)
			{
				Log.Error(Tag, "ToggleKeepScreenOn: Exception on lock release." + e.Message + e.StackTrace);
			}
		}
 private void ReleaseWakeLock()
 {
     if (null == _wakeLock) return;
     _wakeLock.Release();
     _wakeLock = null;
 }
        public void SetService(AndroidSensusService service)
        {
            _service = service;

            if (_service == null)
            {
                if (_connectivityManager != null)
                    _connectivityManager.Dispose();

                if (_notificationManager != null)
                    _notificationManager.Dispose();

                if (_textToSpeech != null)
                    _textToSpeech.Dispose();

                if (_wakeLock != null)
                    _wakeLock.Dispose();
            }
            else
            {
                _connectivityManager = _service.GetSystemService(Context.ConnectivityService) as ConnectivityManager;
                _notificationManager = _service.GetSystemService(Context.NotificationService) as NotificationManager;
                _textToSpeech = new AndroidTextToSpeech(_service);
                _wakeLock = (_service.GetSystemService(Context.PowerService) as PowerManager).NewWakeLock(WakeLockFlags.Partial, "SENSUS");
                _wakeLockAcquisitionCount = 0;
                _deviceId = Settings.Secure.GetString(_service.ContentResolver, Settings.Secure.AndroidId);

                // must initialize after _deviceId is set
                if (Insights.IsInitialized)
                    Insights.Identify(_deviceId, "Device ID", _deviceId);
            }
        }
Example #50
0
        public override void OnCreate()
        {
            base.OnCreate();
            try
            {
                //_logger = new Logger(Environment.ExternalStorageDirectory.AbsolutePath);
                _powerManager = (PowerManager)BaseContext.GetSystemService(PowerService);
                _sensorManager = (SensorManager)BaseContext.GetSystemService(SensorService);
                _wakeLockPartial = _powerManager.NewWakeLock(WakeLockFlags.Partial, _tag);
                _screenOffReceiver = new WakeUpServiceReceiver(() =>
                {
                    new Handler().PostDelayed(() =>
                    {
                        UnregisterListener();
                        RegisterListener();
                        Log.Debug("WakeUpServiceReceiver", "Screen turned off.");
                    }, 500);
                });
                RegisterReceiver(_screenOffReceiver, new IntentFilter(Intent.ActionScreenOff));

                Status = ServiceStatus.STARTED;
                Log.Debug("WakeUpService", "Service started.");
            }
            catch (Exception ex)
            {
                Log.Error("WakeUpService", ex.ToString());
                Status = ServiceStatus.FAILED;
            }
        }