Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions pythonforandroid/recipes/android/src/android/broadcast.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ def onReceive(self, context, intent):
def __init__(self, callback, actions=None, categories=None):
super().__init__()
self.callback = callback
self._is_registered = False

if not actions and not categories:
raise Exception('You need to define at least actions or categories')
Expand Down Expand Up @@ -58,15 +59,36 @@ def _expand_partial_name(partial_name):
self.receiver_filter.addCategory(x)

def start(self):
Handler = autoclass('android.os.Handler')

if hasattr(self, 'handlerthread') and self.handlerthread.isAlive():
print("HandlerThread already running, skipping start")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be better with a logger instead of print.

return

HandlerThread = autoclass('android.os.HandlerThread')
self.handlerthread = HandlerThread('handlerthread')
self.handlerthread.start()

if self._is_registered:
print("[BroadcastReceiver] Already registered.")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be better with a logger instead of print.

return

Handler = autoclass('android.os.Handler')
self.handler = Handler(self.handlerthread.getLooper())
self.context.registerReceiver(
self.receiver, self.receiver_filter, None, self.handler)
self._is_registered = True

def stop(self):
self.context.unregisterReceiver(self.receiver)
self.handlerthread.quit()
try:
self.context.unregisterReceiver(self.receiver)
self._is_registered = False
except Exception as e:
print("[BroadcastReceiver] unregisterReceiver failed:", e)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would be better with a logger instead of print.


if hasattr(self, 'handlerthread'):
self.handlerthread.quitSafely()
self.handlerthread = None
self.handler = None

@property
def context(self):
Expand Down
Loading