@blotch/angular-lynx-native 22.3.2 → 22.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +8 -2
  2. package/dist/android/project.d.ts +27 -3
  3. package/dist/android/project.d.ts.map +1 -1
  4. package/dist/android/project.js +80 -9
  5. package/dist/eject.d.ts.map +1 -1
  6. package/dist/eject.js +1 -0
  7. package/dist/files.d.ts +24 -0
  8. package/dist/files.d.ts.map +1 -0
  9. package/dist/files.js +41 -0
  10. package/dist/generate.d.ts +17 -2
  11. package/dist/generate.d.ts.map +1 -1
  12. package/dist/generate.js +68 -17
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +8 -1
  15. package/dist/ios/project.d.ts +21 -2
  16. package/dist/ios/project.d.ts.map +1 -1
  17. package/dist/ios/project.js +58 -2
  18. package/dist/options.d.ts +68 -0
  19. package/dist/options.d.ts.map +1 -1
  20. package/dist/options.js +27 -0
  21. package/dist/permissions.d.ts.map +1 -1
  22. package/dist/permissions.js +18 -3
  23. package/dist/plugins.d.ts +245 -0
  24. package/dist/plugins.d.ts.map +1 -0
  25. package/dist/plugins.js +1244 -0
  26. package/package.json +1 -1
  27. package/templates/android/README.md +12 -4
  28. package/templates/android/app/build.gradle.kts +27 -9
  29. package/templates/android/app/src/main/AndroidManifest.xml +5 -0
  30. package/templates/android/app/src/main/java/dev/angularlynx/shell/AngularLynxPlugins.kt +13 -0
  31. package/templates/android/app/src/main/java/dev/angularlynx/shell/AudioRecorderModule.kt +520 -0
  32. package/templates/android/app/src/main/java/dev/angularlynx/shell/EdgeToEdgeOverlay.kt +24 -0
  33. package/templates/android/app/src/main/java/dev/angularlynx/shell/EngineThreadHint.kt +156 -0
  34. package/templates/android/app/src/main/java/dev/angularlynx/shell/GeolocationModule.kt +557 -0
  35. package/templates/android/app/src/main/java/dev/angularlynx/shell/HostElementUI.kt +331 -0
  36. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePickerModule.kt +143 -0
  37. package/templates/android/app/src/main/java/dev/angularlynx/shell/ImagePipeline.kt +83 -0
  38. package/templates/android/app/src/main/java/dev/angularlynx/shell/MainActivity.kt +153 -9
  39. package/templates/android/app/src/main/java/dev/angularlynx/shell/NetworkStatus.kt +121 -0
  40. package/templates/android/app/src/main/java/dev/angularlynx/shell/PermissionRequests.kt +10 -0
  41. package/templates/android/app/src/main/java/dev/angularlynx/shell/PhotoLibraryModule.kt +203 -16
  42. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellApplication.kt +1 -8
  43. package/templates/android/app/src/main/java/dev/angularlynx/shell/ShellModule.kt +11 -1
  44. package/templates/android/app/src/main/res/xml/share_paths.xml +7 -2
  45. package/templates/ios/App/AngularLynxPlugins.swift +22 -0
  46. package/templates/ios/App/AnimationFrameRate.swift +66 -0
  47. package/templates/ios/App/AppDelegate.swift +3 -1
  48. package/templates/ios/App/AudioRecorderModule.swift +433 -0
  49. package/templates/ios/App/GeolocationModule.swift +455 -0
  50. package/templates/ios/App/HostElementUI.swift +270 -0
  51. package/templates/ios/App/ImagePickerModule.swift +160 -1
  52. package/templates/ios/App/LynxViewController.swift +66 -5
  53. package/templates/ios/App/NetworkStatus.swift +41 -0
@@ -13,6 +13,9 @@ import android.os.Handler
13
13
  import android.os.Looper
14
14
  import android.provider.Settings
15
15
  import android.util.Log
16
+ import android.util.Size
17
+ import android.view.MotionEvent
18
+ import android.view.View.MeasureSpec
16
19
  import android.view.accessibility.AccessibilityManager
17
20
  import android.widget.FrameLayout
18
21
  import androidx.activity.BackEventCompat
@@ -49,6 +52,10 @@ import com.lynx.xelement.XElementBehaviors
49
52
  class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
50
53
  private lateinit var lynxView: LynxView
51
54
 
55
+ // Android's hint that Lynx's engine thread has work coming, given at
56
+ // every touch (EngineThreadHint.kt). Android 12 and later.
57
+ private var engineThreadHint: EngineThreadHint? = null
58
+
52
59
  // Whether the page draws under the system bars and the cutout:
53
60
  // angular.json's edgeToEdge, which app/build.gradle.kts writes as a
54
61
  // resource.
@@ -71,6 +78,11 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
71
78
  private var safeArea = Insets.NONE
72
79
  private var hasCutout = false
73
80
 
81
+ // The window's size and the LynxView's, in px, as the container was last
82
+ // measured (see updateSizes). Null until the first measure.
83
+ private var windowSize: Size? = null
84
+ private var viewportSize: Size? = null
85
+
74
86
  // Where the app is, for LynxAppState, sent in the global props and again
75
87
  // as the activity's lifecycle moves: "active" from onResume, "inactive"
76
88
  // from onPause and onStart, and "background" from onStop. It starts
@@ -89,6 +101,10 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
89
101
  // it, so a resumed activity is the one with the focus.
90
102
  private var topResumed = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
91
103
 
104
+ // Whether the phone is online, for LynxNetwork: sent in the global props,
105
+ // and again each time it changes. Closed in onDestroy.
106
+ private var networkStatus: NetworkStatus? = null
107
+
92
108
  // Sends the accessibility settings again when the user changes one while
93
109
  // the app is open: Remove animations (the animator duration scale), the
94
110
  // contrast level (Android 14) and high contrast text (Android 16). The
@@ -176,13 +192,41 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
176
192
  imagePicked = null
177
193
  done(uri)
178
194
  }
195
+ // angular-lynx:image-picker-camera
196
+ // The camera app behind LynxImagePicker's source: 'camera', registered as
197
+ // the Photo Picker is. Only an app with permissions.camera keeps these
198
+ // lines (@blotch/angular-lynx-native's android/project.ts).
199
+ private var photoTaken: ((Boolean) -> Unit)? = null
200
+ private val camera = registerForActivityResult(ActivityResultContracts.TakePicture()) { taken ->
201
+ val done = photoTaken ?: return@registerForActivityResult
202
+ photoTaken = null
203
+ done(taken)
204
+ }
205
+ // /angular-lynx:image-picker-camera
179
206
  private val imagePickerHost = object : ImagePickerModule.Host {
180
207
  override fun pickImage(done: (Uri?) -> Unit): Boolean {
181
208
  if (imagePicked != null) return false
209
+ // angular-lynx:image-picker-camera
210
+ // One of the two at a time, as takePicture checks the other way.
211
+ if (photoTaken != null) return false
212
+ // /angular-lynx:image-picker-camera
182
213
  imagePicked = done
183
214
  imagePicker.launch(PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))
184
215
  return true
185
216
  }
217
+
218
+ // angular-lynx:image-picker-camera
219
+ override fun takePicture(output: Uri, done: (Boolean) -> Unit): Boolean {
220
+ if (photoTaken != null || imagePicked != null) return false
221
+ // Throws ActivityNotFoundException before anything is kept, so a
222
+ // phone without a camera app can try again.
223
+ camera.launch(output)
224
+ photoTaken = done
225
+ return true
226
+ }
227
+
228
+ override val permissions: PermissionHost get() = permissionHost
229
+ // /angular-lynx:image-picker-camera
186
230
  }
187
231
 
188
232
  // Android's permission prompt, which the modules that need a runtime
@@ -203,6 +247,8 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
203
247
  permissionPrompt.launch(names)
204
248
  return true
205
249
  }
250
+
251
+ override fun canAskAgain(name: String): Boolean = shouldShowRequestPermissionRationale(name)
206
252
  }
207
253
 
208
254
  // The document picker and save screen behind LynxFilePicker (see
@@ -262,6 +308,13 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
262
308
  }
263
309
  // /angular-lynx:share-target
264
310
 
311
+ override fun dispatchTouchEvent(event: MotionEvent): Boolean {
312
+ // Before the touch reaches Lynx, so the engine thread is on its way
313
+ // to a faster core by the time the page's handler runs.
314
+ engineThreadHint?.touched(event)
315
+ return super.dispatchTouchEvent(event)
316
+ }
317
+
265
318
  override fun onCreate(savedInstanceState: Bundle?) {
266
319
  // The splash screen (themes.xml's Theme.AngularLynxShell.Starting),
267
320
  // before anything else: it switches the activity to the app's own
@@ -324,6 +377,9 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
324
377
  // --platform android` runs, the dev server's (DevServer.kt).
325
378
  val bundleUrl = DevServer.bundleUrl(this) ?: BundleAssets.MAIN_BUNDLE
326
379
  builtFontScale = textScale(resources.configuration)
380
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
381
+ engineThreadHint = EngineThreadHint(this)
382
+ }
327
383
  lynxView = LynxViewBuilder().apply {
328
384
  // Lynx's engine thread, which runs the main thread's JavaScript
329
385
  // (the whole Angular app), layout and Lynx's animator, gets a
@@ -379,11 +435,12 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
379
435
  registerModule(BiometricsModule.NAME, BiometricsModule::class.java, this@MainActivity)
380
436
  // /angular-lynx:biometrics
381
437
  // Saving to the photo library behind LynxPhotoLibrary
382
- // (PhotoLibraryModule.kt). Only an app with permissions.savePhotos
383
- // keeps these lines and the module (@blotch/angular-lynx-native's
384
- // android/project.ts).
438
+ // (PhotoLibraryModule.kt), which asks for the storage permission
439
+ // through this activity on Android 7 to 9. Only an app with
440
+ // permissions.savePhotos keeps these lines and the module
441
+ // (@blotch/angular-lynx-native's android/project.ts).
385
442
  // angular-lynx:photo-library
386
- registerModule(PhotoLibraryModule.NAME, PhotoLibraryModule::class.java, null)
443
+ registerModule(PhotoLibraryModule.NAME, PhotoLibraryModule::class.java, permissionHost)
387
444
  // /angular-lynx:photo-library
388
445
  // The code scanner behind LynxBarcodeScanner
389
446
  // (BarcodeScannerModule.kt), which opens over this activity. Only
@@ -419,6 +476,14 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
419
476
  // and Play's advertising ID library.
420
477
  registerModule(TrackingModule.NAME, TrackingModule::class.java, null)
421
478
  // /angular-lynx:tracking
479
+ // angular-lynx:audio-recorder
480
+ // The microphone's recorder behind LynxAudioRecorder
481
+ // (AudioRecorderModule.kt), which asks for RECORD_AUDIO through
482
+ // this activity's prompt. An app whose angular.json doesn't set
483
+ // permissions.microphone is built without the module and these
484
+ // lines.
485
+ registerModule(AudioRecorderModule.NAME, AudioRecorderModule::class.java, permissionHost)
486
+ // /angular-lynx:audio-recorder
422
487
  // angular-lynx:nfc
423
488
  // NFC reader mode behind LynxNfc (NfcModule.kt), in this activity.
424
489
  // An app whose angular.json doesn't set permissions.nfc is built
@@ -463,6 +528,14 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
463
528
  optionalModule(BLUETOOTH_MODULE_CLASS)?.let {
464
529
  registerModule(BLUETOOTH_MODULE, it, permissionHost)
465
530
  }
531
+ // angular-lynx:geolocation
532
+ // Where the phone is, behind LynxGeolocation
533
+ // (GeolocationModule.kt), which asks for the location
534
+ // permissions through this activity. An app whose angular.json
535
+ // doesn't set permissions.location is built without the module
536
+ // and these lines.
537
+ registerModule(GeolocationModule.NAME, GeolocationModule::class.java, permissionHost)
538
+ // /angular-lynx:geolocation
466
539
  // <canvas>'s WebGL (WebGLModule.kt), which the runtime calls from
467
540
  // the main thread, where Angular runs: main-thread modules let
468
541
  // it get its answers synchronously, with lynx.module(name). Lynx
@@ -492,6 +565,11 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
492
565
  // Live reload, in the debug build: it renders the bundle again
493
566
  // after every edit.
494
567
  DevServer.register(this) { lynxView.renderTemplateUrl(bundleUrl, "") }
568
+ // The app's native plugins' modules and elements (angular.json's
569
+ // `nativePlugins`), after the shell's own and the dev server's,
570
+ // as on iOS. A module gets this activity as its param, as the
571
+ // shell's own modules that need one do.
572
+ AngularLynxPlugins.register(this, this@MainActivity)
495
573
  }.build(this)
496
574
  // The LynxView is focusable, so it takes focus whenever the window
497
575
  // isn't in touch mode: after any key press, from a hardware keyboard,
@@ -530,7 +608,25 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
530
608
  // variables on the page. With "edgeToEdge": false in angular.json
531
609
  // the page sits inside the safe area, and the runtime keeps env() at
532
610
  // 0. The iOS shell matches.
533
- val container = FrameLayout(this)
611
+ // The container fills the window, edge to edge, so each measure brings
612
+ // the window's size, and the LynxView's, before the LynxView is
613
+ // measured: a phone folding or unfolding, a rotation, or split screen
614
+ // resizing the window (see updateSizes).
615
+ val container = object : FrameLayout(this) {
616
+ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
617
+ if (MeasureSpec.getMode(widthMeasureSpec) == MeasureSpec.EXACTLY &&
618
+ MeasureSpec.getMode(heightMeasureSpec) == MeasureSpec.EXACTLY
619
+ ) {
620
+ val width = MeasureSpec.getSize(widthMeasureSpec)
621
+ val height = MeasureSpec.getSize(heightMeasureSpec)
622
+ updateSizes(
623
+ Size(width, height),
624
+ Size(width - paddingLeft - paddingRight, height - paddingTop - paddingBottom),
625
+ )
626
+ }
627
+ super.onMeasure(widthMeasureSpec, heightMeasureSpec)
628
+ }
629
+ }
534
630
  container.addView(lynxView, FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)
535
631
  ViewCompat.setOnApplyWindowInsetsListener(container) { view, insets ->
536
632
  val bars = insets.getInsets(
@@ -580,6 +676,9 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
580
676
  highContrastTextListener = listener
581
677
  }
582
678
 
679
+ // Before the first props, which it reads synchronously.
680
+ networkStatus = NetworkStatus(this) { sendGlobalProps() }
681
+
583
682
  onBackPressedDispatcher.addCallback(this, backHandler)
584
683
  // Sent before the bundle loads, so the app starts with the theme and
585
684
  // the language. The insets follow once the window reports them.
@@ -659,6 +758,11 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
659
758
  //
660
759
  // A new font size arrives here too (the manifest lists fontScale), and the
661
760
  // page's root font size, with every rem, takes the new scale at once.
761
+ //
762
+ // So does a phone folding or unfolding, or rotating, but the new size is
763
+ // sent from the container's measure instead (updateSizes), which follows
764
+ // every change in the window's size, including split screen's, and comes
765
+ // before the LynxView is measured at it.
662
766
  override fun onConfigurationChanged(newConfig: Configuration) {
663
767
  super.onConfigurationChanged(newConfig)
664
768
  updateWindowAppearance()
@@ -666,6 +770,31 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
666
770
  lynxView.updateGlobalProps(globalProps(newConfig))
667
771
  }
668
772
 
773
+ // Lynx 4 lays the page out again at a new size by itself, once the host
774
+ // tells it, in Lynx's foldable guide's order: the window's size, which
775
+ // rpx lengths are a 750th of, then the LynxView's, which %, vw, vh and
776
+ // @media measure against, then the global props LynxViewport reads. The
777
+ // window's is in px: LynxView.updateScreenMetrics divides it by the
778
+ // density itself. It's the window's rather than the display's, as on iOS,
779
+ // so a window sharing the screen in split screen is the one measured.
780
+ //
781
+ // Measuring gives a new size before the LynxView's onMeasure, which
782
+ // updates the viewport by itself, so the page is laid out once at its new
783
+ // size. A new window size alone doesn't lay the page out again (Lynx
784
+ // only takes note of it), so the viewport is updated here too: with the
785
+ // size it already has, that's what applies the new rpx.
786
+ private fun updateSizes(window: Size, viewport: Size) {
787
+ if (window == windowSize && viewport == viewportSize) return
788
+ if (window != windowSize) lynxView.updateScreenMetrics(window.width, window.height)
789
+ windowSize = window
790
+ viewportSize = viewport
791
+ lynxView.updateViewport(
792
+ MeasureSpec.makeMeasureSpec(viewport.width, MeasureSpec.EXACTLY),
793
+ MeasureSpec.makeMeasureSpec(viewport.height, MeasureSpec.EXACTLY),
794
+ )
795
+ sendGlobalProps()
796
+ }
797
+
669
798
  // How much larger than the default the user's font size is (Settings >
670
799
  // Display > Font size): 1 at the default, up to 2 on Android 14 and
671
800
  // later. Capped at angular.json's textScaling.max, and 1 with
@@ -695,10 +824,10 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
695
824
  * (LynxSafeArea), `appLocale` (LynxLocale), `appTimeZone` (the `intl`
696
825
  * build option's Intl.DateTimeFormat), the accessibility settings and
697
826
  * text scale (LynxAccessibilitySettings), `appState` (LynxAppState),
698
- * `osVersion` (LynxSystemInfo) and `initialURL` (LynxLinking and the
699
- * router), plus the
700
- * safe-area insets in dp and `edgeToEdge`, which env(safe-area-inset-*)
701
- * reads. The iOS shell sends the same keys, and Lynx Explorer sends theme
827
+ * `online` (LynxNetwork), `osVersion` (LynxSystemInfo), `initialURL`
828
+ * (LynxLinking and the router) and the window's and the LynxView's sizes in dp (LynxViewport),
829
+ * plus the safe-area insets in dp and `edgeToEdge`, which
830
+ * env(safe-area-inset-*) reads. The iOS shell sends the same keys, and Lynx Explorer sends theme
702
831
  * and isNotchScreen too. Android 12 and later also send the wallpaper's
703
832
  * colors, `dynamicColors` (LynxTheme.dynamicColors), which iOS has no
704
833
  * equivalent of.
@@ -727,6 +856,8 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
727
856
  // (LynxAccessibilitySettings.textScale).
728
857
  "textScale" to textScale(config),
729
858
  "appState" to appState,
859
+ // Whether the phone has a connection to the internet.
860
+ "online" to (networkStatus?.online ?: true),
730
861
  )
731
862
  // The user's language as a BCP 47 tag, such as "fr-FR".
732
863
  ConfigurationCompat.getLocales(config)[0]?.let { props["appLocale"] = it.toLanguageTag() }
@@ -734,6 +865,17 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
734
865
  // option's Intl.DateTimeFormat formats in the device's zone by default,
735
866
  // which it reads from the engine's local time, and names it with this.
736
867
  props["appTimeZone"] = java.util.TimeZone.getDefault().id
868
+ // The sizes Lynx's foldable guide names, in dp, once the container has
869
+ // been measured: the window's, and the LynxView's, which is smaller
870
+ // with "edgeToEdge": false and while the keyboard is open.
871
+ windowSize?.let {
872
+ props["screenWidth"] = it.width / density
873
+ props["screenHeight"] = it.height / density
874
+ }
875
+ viewportSize?.let {
876
+ props["viewportWidth"] = it.width / density
877
+ props["viewportHeight"] = it.height / density
878
+ }
737
879
  DynamicColors.read(this)?.let { props["dynamicColors"] = it }
738
880
  // The link that started the app, which the router starts at. In
739
881
  // every update, since each sends the whole set.
@@ -813,6 +955,8 @@ class MainActivity : FragmentActivity(), ShellModule.Host, WebAuthModule.Host {
813
955
  // Only this activity's own: a recreated one has set its own already.
814
956
  if (ShareTargetModule.arrived === shareArrived) ShareTargetModule.arrived = null
815
957
  // /angular-lynx:share-target
958
+ engineThreadHint?.close()
959
+ networkStatus?.close()
816
960
  contentResolver.unregisterContentObserver(animationScaleObserver)
817
961
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {
818
962
  (contrastListener as UiModeManager.ContrastChangeListener?)?.let {
@@ -0,0 +1,121 @@
1
+ package dev.angularlynx.shell
2
+
3
+ import android.content.Context
4
+ import android.net.ConnectivityManager
5
+ import android.net.Network
6
+ import android.net.NetworkCapabilities
7
+ import android.os.Build
8
+ import android.os.Handler
9
+ import android.os.Looper
10
+
11
+ /**
12
+ * Whether the phone has a connection to the internet, for LynxNetwork, which
13
+ * MainActivity sends in the `online` global prop. Lynx tells the app's code
14
+ * nothing about the connection, and has no `navigator.onLine`, so the shell
15
+ * watches it itself.
16
+ *
17
+ * Online while the default network can reach the internet and Android has
18
+ * checked that it does (NET_CAPABILITY_VALIDATED): a Wi-Fi network behind a
19
+ * captive portal, or one with no way out, counts as offline, as the status
20
+ * bar's "!" shows. It needs ACCESS_NETWORK_STATE, a permission Android grants
21
+ * at install without asking.
22
+ *
23
+ * [onChange] is called on the main thread each time [online] changes, and
24
+ * only then: a new network with the same answer (Wi-Fi to cellular) would
25
+ * only make the app run its change detection for nothing. [close] stops it.
26
+ */
27
+ class NetworkStatus(context: Context, private val onChange: (Boolean) -> Unit) : AutoCloseable {
28
+ private val connectivity = context.getSystemService(ConnectivityManager::class.java)
29
+
30
+ // The callbacks come on a ConnectivityManager thread, and the LynxView
31
+ // takes its updates on the main one. The overload that takes a Handler
32
+ // needs Android 8, above the app's minSdk, so each callback posts.
33
+ private val main = Handler(Looper.getMainLooper())
34
+
35
+ // The default network the callbacks last named, on the main thread. A
36
+ // switch to another one can report the old one lost after the new one is
37
+ // available, which mustn't take the app offline.
38
+ private var current: Network? = null
39
+
40
+ // Set by close(), on the main thread. A callback already running on the
41
+ // ConnectivityManager thread as the callback is unregistered can still
42
+ // post after close() cleared the queue, and its update mustn't reach a
43
+ // LynxView that has gone.
44
+ private var closed = false
45
+
46
+ private val callback = object : ConnectivityManager.NetworkCallback() {
47
+ override fun onAvailable(network: Network) {
48
+ // Android 8 and later always follow onAvailable with
49
+ // onCapabilitiesChanged, which answers for the network. Android 7
50
+ // may not, so a network that is already validated as it becomes
51
+ // the default would otherwise never take the app online. Its
52
+ // capabilities are read once the main thread runs the post, not in
53
+ // the callback, where a ConnectivityManager call can race the
54
+ // update it is reporting.
55
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) return
56
+ main.post {
57
+ current = network
58
+ update(isOnline(connectivity.getNetworkCapabilities(network)))
59
+ }
60
+ }
61
+
62
+ override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
63
+ val online = isOnline(capabilities)
64
+ main.post {
65
+ current = network
66
+ update(online)
67
+ }
68
+ }
69
+
70
+ override fun onLost(network: Network) {
71
+ main.post {
72
+ if (current == null || current == network) {
73
+ current = null
74
+ update(false)
75
+ }
76
+ }
77
+ }
78
+ }
79
+
80
+ init {
81
+ // Registered before the first read, so no change can fall between the
82
+ // two: Android reports the default network to a new callback, but says
83
+ // nothing when there is none, so a network lost after the read and
84
+ // before the registration would leave the app online until the next
85
+ // change. A loss after the registration reaches the callback, whose
86
+ // posts run after this.
87
+ connectivity.registerDefaultNetworkCallback(callback)
88
+ }
89
+
90
+ /**
91
+ * Whether the phone is online now. Read synchronously from the active
92
+ * network as this starts, so the first global props, which go out from
93
+ * onCreate before any callback, are already right.
94
+ */
95
+ var online: Boolean = isOnline(connectivity.getNetworkCapabilities(connectivity.activeNetwork))
96
+ private set
97
+
98
+ private fun update(online: Boolean) {
99
+ if (closed || this.online == online) return
100
+ this.online = online
101
+ onChange(online)
102
+ }
103
+
104
+ /**
105
+ * Stops watching, as the activity goes. Android caps how many callbacks
106
+ * an app can hold, and keeps each one, and what it reaches, until it's
107
+ * unregistered.
108
+ */
109
+ override fun close() {
110
+ closed = true
111
+ connectivity.unregisterNetworkCallback(callback)
112
+ main.removeCallbacksAndMessages(null)
113
+ }
114
+
115
+ private companion object {
116
+ fun isOnline(capabilities: NetworkCapabilities?): Boolean =
117
+ capabilities != null &&
118
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) &&
119
+ capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
120
+ }
121
+ }
@@ -22,4 +22,14 @@ interface PermissionHost {
22
22
  * declare (which counts as refused).
23
23
  */
24
24
  fun requestPermissions(names: Array<String>, done: (Map<String, Boolean>) -> Unit): Boolean
25
+
26
+ /**
27
+ * Whether Android would show its prompt again for [name], which the
28
+ * person refused: true after a refusal they may still change their mind
29
+ * about, false once they've ticked "Don't ask again" (and for a
30
+ * permission never asked for). Only an activity can tell, so a module
31
+ * that reports `denied` and `undetermined` apart asks it here. Any
32
+ * thread.
33
+ */
34
+ fun canAskAgain(name: String): Boolean = false
25
35
  }