Anas Anas - 23 days ago 10
Android Question

Keep Android service aware, not awake

I have a service (for detecting incoming and outgoing calls) that the user can start and stop in my application; the service can start also when device is restarted.

Now I'm running on a situation where the service is not "awake" when the device is asleep; and when a call is received the service is not yet awake to handle that incoming call.

My question is how to make my service aware of this condition without keeping a wakelock for it?

If the wakelock is the only way to solve this, then what should be the best implementation for it?

Answer

add in manifest:

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

Now in your service:

PowerManager powerManager;
PowerManager.WakeLock wakeLock;

@Override
    public void onCreate() {
        super.onCreate();
        powerManager = (PowerManager) getSystemService(POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "NOTIFY");

    }

now,

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        wakeLock.acquire();
        handleSERVICE(intent);
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        wakeLock.release();
    }
Comments