Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep activity running over screen lock when the screens alseep

Tags:

android

So i built an app that functions as a lock screen replacement. I use a broadcast receiver and a service to start my activity after Intent.ACTION_SCREEN_OFF. So that every time the user locks the screen my activity starts, then when they press the unlock button my activity is already running over the lock screen. But this only works if the user tries to wake up/unlock the phone after a short amount of time. If they wait too long the activity has vanished. I'm not sure why this is happening and what I can do to keep the activity there no matter how long the user waits to try to unlock their phone.

I thought about and tried listening for Intent.ACTION_SCREEN_ON but then there is a delay between the time when the user presses the power button on their phone to wake it up and when the app loads and shows up on the screen. During this gap the user can see the android OS

like image 672
Peter Avatar asked Jul 18 '12 16:07

Peter


2 Answers

What if you use a wakelock. For example:

@Override
public void onCreate(Bundle savedInstanceState) { 
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
    wl.acquire();
    // do your things, even when screen is off
}


@Override
protected void onDestroy() {
    wl.release();
}

You must also have a wakelock permission is AndroidManifest.xml

uses-permission android:name="android.permission.WAKE_LOCK"
like image 171
Thomas Kaliakos Avatar answered Nov 12 '22 01:11

Thomas Kaliakos


One way you might want to try is to make sure you app never sleeps. On short sleeps it will stay running. On long sleeps your app itself is asleep. I was able to get around this myself with using the PowerManager.Wakelock. Only issue is that this will drain more battery if your app is using cpu cycles.

/** wake lock on the app so it continues to run in background if phone tries to sleep.*/
PowerManager.WakeLock wakeLock;

@Override
public void onCreate(Bundle savedInstanceState) {
    ...

    // keep the program running even if phone screen and keyboard go to sleep
    PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);

    ...
}

// use this when screen sleeps
wakeLock.acquire();

// use this once when phone stops sleeping
wakeLock.release();
like image 1
JPM Avatar answered Nov 12 '22 02:11

JPM