简体   繁体   中英

Prevent app from going on OnPause when turning screen off using partial wakelock

I'm trying to catch the volume Up/Down button press with the screen off, but despite acquiring a wakelock the app doesn't stay in the foreground when pressing the lock button. I have a breakpoint in the OnPause method and it gets hit when the screen turns off, and I can confirm that the wakelock is on through ADB terminal with the command:

adb shell dumpsys power

I omitted the volume buttons events since they're not relevant, but they do work when the screen is on. I don't know what I'm missing, maybe I'm missunderstanding how the wakelock is supposed to behave?

I'm testing it in an emulator with Android 6.0 and in a physical phone with Android 7.1.2. Thanks in advance for any help..

Button getLockBtn;

PowerManager _powerManager;
PowerManager.WakeLock _wakeLock;


protected override void OnCreate(Bundle savedInstanceState)
{
    base.OnCreate(savedInstanceState);
    RequestWindowFeature(WindowFeatures.NoTitle);
    SetContentView(Resource.Layout.Main);

    getLockBtn = FindViewById<Button>(Resource.Id.GetLockBtn);

    _powerManager = (PowerManager)GetSystemService(PowerService);
    _wakeLock = _powerManager.NewWakeLock(WakeLockFlags.Partial, "MyTag");

    getLockBtn.Click += (s, e) =>
    {
        if (_wakeLock.IsHeld)
        {
            _wakeLock.Release();
            getLockBtn.Text = "Get lock";
            //Remove the notification
        }
        else
        {
            //Here I show a notification
            _wakeLock.Acquire();
            getLockBtn.Text = "Release lock";
        }
    };
}

So how do apps like Google Maps achieve that behavior

When the screen is locked, the volume control comes from the system, and it is not the time to apply the control itself.Google Maps do nothing with the volume.

Your problem may not be the use of the volume button under the lock screen, but the program can still work when you lock the screen.

If you want a task to continue running, even when your Activity is not active, you need to use a Service. https://developer.android.com/guide/components/services.html . Also can and a Notification to show something on the lock screen. https://developer.android.com/guide/topics/ui/notifiers/notifications.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM