user1529891
user1529891

Reputation:

Android; notification while device is in sleep state

I have a service that runs in the background that notifies to the status bar with a vibrate. However, when my phone goes into sleep state it no longer notifies with vibrates. How can I enable this functionality while the device is in sleep state?

Upvotes: 0

Views: 2614

Answers (3)

Sang Nguyễn
Sang Nguyễn

Reputation: 15

You could use wake lock follow this link: Keep the CPU on

Here is how you set a wake lock directly

Kotlin:

val wakeLock: PowerManager.WakeLock =
        (getSystemService(Context.POWER_SERVICE) as PowerManager).run {
            newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyApp::MyWakelockTag").apply {
                acquire()
            }
        }

Java:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
        "MyApp::MyWakelockTag");
wakeLock.acquire();

To release the wake lock, both Java and Kotlin:

wakeLock.release()

Remember, to use a wake lock, the first step is to add the WAKE_LOCK permission to your application's manifest file:

<uses-permission android:name="android.permission.WAKE_LOCK" />

Or you also use a broadcast receiver that keeps the device awake Here is link

Upvotes: 0

BlueLeaf
BlueLeaf

Reputation: 223

First take care of the permissions (in the manifest file):

<uses-permission android:name="android.permission.WAKE_LOCK" />

Then, most preferably use this in the Application file, or wherever:

PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakelockTag");
if(/*condition*/) {
    wakeLock.acquire(); //keep CPU awake
} else {
    wakeLock.release(); //disable keep CPU awake
}

Although it is a pretty cool feature, with great power comes great responsibility: It drains your battery life, hence use it responsibility.

I prefer to release this PARTIAL_WAKE_LOCK by night as by base users do not use it beyond business hours.

Upvotes: 0

bladefury
bladefury

Reputation: 815

Checkout PARTIAL_WAKE_LOCK. You can keep your service running while screen is off. according to the developers doc, it's quite simple:

PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Tag");
wl.acquire();
..cpu will stay running on during this section..
wl.release();

In your case, if you want to keep your service always running, acquire your lock in onStartCommand() and release in onDestroy().

Upvotes: 1

Related Questions