Skip to content

Fix broadcast receiver #3168

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
Changes from all 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")
return

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

if self._is_registered:
print("[BroadcastReceiver] Already registered.")
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)

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

@property
def context(self):
Expand Down
Loading