do I need a wake lock in my broadcastreceiver if I'm not starting a service or an activity?

心不动则不痛 提交于 2019-12-04 05:51:33

In this receiver I'm only querying a register from the database, and launching a notification.

Do not do database I/O on the main application thread.

I readed that a wake lock is needed when a service or an activity is started from a broadcast receiver, but, do I need a wake lock if I only want to show a notificacion (in the notification panel)?

In general, no, you would not need a WakeLock from a BroadcastReceiver, even one that is invoked via a _WAKEUP alarm. AlarmManager guarantees in this case that it will keep the device awake using its own WakeLock.

However, again, in this case, you really should not be doing database I/O on the main application thread, and onReceive() is called on the main application thread. The proper pattern here is that you move your "querying a register from the database, and launching a notification" to an IntentService, started by your BroadcastReceiver, so that the work is done on a background thread. This will require a WakeLock, as you are now doing work outside of onReceive(). I have a WakefulIntentService that manages the WakeLock for you, if you wish to use it.

Yes, it is necessary. I remember that in the Kernel level, the CPU will be kept running for about 5 seconds. So if you cannot finishing send your notification within 5 seconds, you have to grasp a wake lock. And release it after you finished your work.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!