Keeping a background service alive on Android

后端 未结 3 594
名媛妹妹
名媛妹妹 2021-01-23 06:22

In reference to Accelerometer seems to only work for a few seconds?

I\'m using the BOOT_COMPLETED broadcast event to call the following:

public class OnB         


        
3条回答
  •  囚心锁ツ
    2021-01-23 06:41

    You need to use a Partial Wakelock with the service. If your service is interactive with the user, you might consider making the service foreground.

    This is a working example for a Partial Wakelock:

    Use this when service is started:

        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock cpuWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        cpuWakeLock.acquire();
    

    When the service is stopped, do call cpuWakeLock.release();

    imports android.support.v4.content.WakefulBroadcastReceiver which Android Studio is telling me doesn't exist.

    You need to import the support library for that.

提交回复
热议问题