|
| 1 | +package be.mygod.reactmap |
| 2 | + |
| 3 | +import android.Manifest |
| 4 | +import android.annotation.SuppressLint |
| 5 | +import android.content.pm.PackageManager |
| 6 | +import android.location.Location |
| 7 | +import android.os.Build |
| 8 | +import android.os.Looper |
| 9 | +import android.util.Log |
| 10 | +import android.webkit.JavascriptInterface |
| 11 | +import android.webkit.WebView |
| 12 | +import androidx.annotation.RequiresPermission |
| 13 | +import androidx.core.app.ComponentActivity |
| 14 | +import androidx.lifecycle.DefaultLifecycleObserver |
| 15 | +import androidx.lifecycle.Lifecycle |
| 16 | +import androidx.lifecycle.LifecycleOwner |
| 17 | +import com.google.android.gms.location.FusedLocationProviderClient |
| 18 | +import com.google.android.gms.location.LocationCallback |
| 19 | +import com.google.android.gms.location.LocationRequest |
| 20 | +import com.google.android.gms.location.LocationResult |
| 21 | + |
| 22 | +class Glocation(private val web: WebView, private val permissionRequestCode: Int) : DefaultLifecycleObserver { |
| 23 | + companion object { |
| 24 | + private const val TAG = "Glocation" |
| 25 | + const val PERMISSION_DENIED = 1 |
| 26 | + const val POSITION_UNAVAILABLE = 2 |
| 27 | + const val TIMEOUT = 3 |
| 28 | + |
| 29 | + fun Location.toGeolocationPosition() = """{ |
| 30 | + coords: { |
| 31 | + latitude: $latitude, |
| 32 | + longitude: $longitude, |
| 33 | + altitude: ${if (hasAltitude()) altitude else null}, |
| 34 | + accuracy: $accuracy, |
| 35 | + altitudeAccuracy: ${ |
| 36 | + if (Build.VERSION.SDK_INT >= 26 && hasVerticalAccuracy()) verticalAccuracyMeters else null |
| 37 | + }, |
| 38 | + heading: ${if (hasBearing()) bearing else null}, |
| 39 | + speed: ${if (hasSpeed()) speed else null}, |
| 40 | + }, |
| 41 | + timestamp: ${time.toULong()}, |
| 42 | + }""" |
| 43 | + |
| 44 | + fun Exception?.toGeolocationPositionError() = """{ |
| 45 | + code: ${if (this is SecurityException) PERMISSION_DENIED else POSITION_UNAVAILABLE}, |
| 46 | + message: ${this?.message?.let { "'$it'" }}, |
| 47 | + }""" |
| 48 | + } |
| 49 | + |
| 50 | + private val activity = web.let { |
| 51 | + it.addJavascriptInterface(this, "_glocation") |
| 52 | + it.context as ComponentActivity |
| 53 | + }.also { it.lifecycle.addObserver(this) } |
| 54 | + private val jsSetup = activity.resources.openRawResource(R.raw.setup).bufferedReader().readText() |
| 55 | + private val client = FusedLocationProviderClient(activity) |
| 56 | + private val pendingRequests = mutableSetOf<Long>() |
| 57 | + private var pendingWatch = false |
| 58 | + private val activeListeners = mutableSetOf<Long>() |
| 59 | + private val callback = object : LocationCallback() { |
| 60 | + override fun onLocationResult(result: LocationResult) { |
| 61 | + val location = result.lastLocation ?: return |
| 62 | + val ids = activeListeners.joinToString() |
| 63 | + Log.d(TAG, "onLocationResult ${location.time}") |
| 64 | + web.evaluateJavascript( |
| 65 | + "navigator.geolocation._watchPositionSuccess([$ids], ${location.toGeolocationPosition()})", null) |
| 66 | + } |
| 67 | + } |
| 68 | + private var requestingLocationUpdates = false |
| 69 | + |
| 70 | + fun clear() { |
| 71 | + pendingRequests.clear() |
| 72 | + activeListeners.clear() |
| 73 | + requestingLocationUpdates = false |
| 74 | + removeLocationUpdates() |
| 75 | + } |
| 76 | + |
| 77 | + fun setupGeolocation() = web.evaluateJavascript(jsSetup, null) |
| 78 | + |
| 79 | + private fun checkPermissions() = when { |
| 80 | + activity.checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == |
| 81 | + PackageManager.PERMISSION_GRANTED -> true |
| 82 | + else -> { |
| 83 | + activity.requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), permissionRequestCode) |
| 84 | + null |
| 85 | + } |
| 86 | + } |
| 87 | + |
| 88 | + fun onRequestPermissionsResult(granted: Boolean) { |
| 89 | + if (pendingRequests.isNotEmpty()) { |
| 90 | + getCurrentPosition(granted, pendingRequests.joinToString()) |
| 91 | + pendingRequests.clear() |
| 92 | + } |
| 93 | + if (pendingWatch) { |
| 94 | + watchPosition(granted) |
| 95 | + pendingWatch = false |
| 96 | + } |
| 97 | + } |
| 98 | + |
| 99 | + @JavascriptInterface |
| 100 | + fun getCurrentPosition(i: Long) { |
| 101 | + Log.d(TAG, "getCurrentPosition($i)") |
| 102 | + when (val granted = checkPermissions()) { |
| 103 | + null -> pendingRequests.add(i) |
| 104 | + else -> getCurrentPosition(granted, i.toString()) |
| 105 | + } |
| 106 | + } |
| 107 | + |
| 108 | + private fun getCurrentPosition(granted: Boolean, ids: String) { |
| 109 | + @SuppressLint("MissingPermission") |
| 110 | + if (granted) client.lastLocation.addOnCompleteListener { task -> |
| 111 | + val location = task.result |
| 112 | + web.evaluateJavascript(if (location == null) { |
| 113 | + "navigator.geolocation._getCurrentPositionError([$ids], ${task.exception.toGeolocationPositionError()})" |
| 114 | + } else "navigator.geolocation._getCurrentPositionSuccess([$ids], ${location.toGeolocationPosition()})", |
| 115 | + null) |
| 116 | + } else web.evaluateJavascript( |
| 117 | + "navigator.geolocation._getCurrentPositionError([$ids], { code: $PERMISSION_DENIED })", null) |
| 118 | + } |
| 119 | + |
| 120 | + @JavascriptInterface |
| 121 | + fun watchPosition(i: Long) { |
| 122 | + Log.d(TAG, "watchPosition($i)") |
| 123 | + if (!activeListeners.add(i) || requestingLocationUpdates || pendingWatch) return |
| 124 | + when (val granted = checkPermissions()) { |
| 125 | + null -> pendingWatch = true |
| 126 | + else -> watchPosition(granted) |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + private fun watchPosition(granted: Boolean) { |
| 131 | + if (granted) @SuppressLint("MissingPermission") { |
| 132 | + requestingLocationUpdates = true |
| 133 | + if (activity.lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)) requestLocationUpdates() |
| 134 | + } else web.evaluateJavascript("navigator.geolocation._watchPositionError([${activeListeners.joinToString()}]," + |
| 135 | + " { code: $PERMISSION_DENIED })", null) |
| 136 | + } |
| 137 | + |
| 138 | + @JavascriptInterface |
| 139 | + fun clearWatch(i: Long) { |
| 140 | + Log.d(TAG, "clearWatch($i)") |
| 141 | + if (!activeListeners.remove(i) || activeListeners.isNotEmpty() || !requestingLocationUpdates) return |
| 142 | + requestingLocationUpdates = false |
| 143 | + removeLocationUpdates() |
| 144 | + } |
| 145 | + |
| 146 | + override fun onStart(owner: LifecycleOwner) { |
| 147 | + @SuppressLint("MissingPermission") |
| 148 | + if (requestingLocationUpdates) requestLocationUpdates() |
| 149 | + } |
| 150 | + override fun onStop(owner: LifecycleOwner) { |
| 151 | + if (requestingLocationUpdates) removeLocationUpdates() |
| 152 | + } |
| 153 | + |
| 154 | + @RequiresPermission(anyOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION]) |
| 155 | + private fun requestLocationUpdates() = client.requestLocationUpdates(LocationRequest.create().apply { |
| 156 | + priority = LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY // enableHighAccuracy - PRIORITY_HIGH_ACCURACY |
| 157 | + // expirationTime = timeout |
| 158 | + // maxWaitTime = maximumAge |
| 159 | + fastestInterval = 1000 |
| 160 | + interval = 4000 |
| 161 | + smallestDisplacement = 5f |
| 162 | + }, callback, Looper.getMainLooper()).addOnCompleteListener { task -> |
| 163 | + if (task.isSuccessful) { |
| 164 | + Log.d(TAG, "Start watching location") |
| 165 | + } else web.evaluateJavascript("navigator.geolocation._watchPositionError([${activeListeners.joinToString()}]," + |
| 166 | + " ${task.exception.toGeolocationPositionError()})", null) |
| 167 | + } |
| 168 | + private fun removeLocationUpdates() = client.removeLocationUpdates(callback).addOnCompleteListener { task -> |
| 169 | + if (task.isSuccessful) Log.d(TAG, "Stop watching location") |
| 170 | + else Log.w(TAG, "Stop watch failed: ${task.exception}") |
| 171 | + } |
| 172 | +} |
0 commit comments