Skip to content

Commit 0da80fd

Browse files
committed
Only create JNI reference once
1 parent 431627c commit 0da80fd

File tree

1 file changed

+19
-5
lines changed
  • src/android/toga_android/widgets

1 file changed

+19
-5
lines changed

src/android/toga_android/widgets/base.py

+19-5
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,31 @@
66
from toga.constants import CENTER, JUSTIFY, LEFT, RIGHT
77

88

9+
def _get_activity(_cache=[]):
10+
"""
11+
Android Toga widgets need a reference to the current activity to pass it as `context` when creating
12+
Android native widgets. This may be useful at any time, so we retain a global JNI ref.
13+
14+
:param _cache: List that is either empty or contains 1 item, the cached global JNI ref
15+
"""
16+
if _cache:
17+
return _cache[0]
18+
# See MainActivity.onCreate() for initialization of .singletonThis:
19+
# https://github.com/beeware/briefcase-android-gradle-template/blob/3.7/%7B%7B%20cookiecutter.formal_name%20%7D%7D/app/src/main/java/org/beeware/android/MainActivity.java
20+
if MainActivity.singletonThis is None:
21+
raise ValueError("Unable to find MainActivity.singletonThis from Python. This is typically set by "
22+
"org.beeware.android.MainActivity.onCreate().")
23+
_cache.append(MainActivity(__jni__=java.NewGlobalRef(MainActivity.singletonThis)))
24+
return _cache[0]
25+
26+
927
class Widget:
1028
def __init__(self, interface):
1129
self.interface = interface
1230
self.interface._impl = self
1331
self._container = None
1432
self.native = None
15-
# In Android, there is only one `app` (i.e., `Activity)`. Android widgets need a reference to
16-
# the current activity to pass it as `context` when creating native Android widgets.
17-
#
18-
# This may happen at any time, so we need a global JNI ref.
19-
self._native_activity = MainActivity(__jni__=java.NewGlobalRef(MainActivity.singletonThis))
33+
self._native_activity = _get_activity()
2034
self.create()
2135
# Immediately re-apply styles. Some widgets may defer style application until
2236
# they have been added to a container.

0 commit comments

Comments
 (0)