Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Android console updates and fixes

Rich Turner2529fa5fd017
diff --git a/console/android/src/main/AndroidManifest.xml b/console/android/src/main/AndroidManifest.xml
index 79f13e27d..07ce568d7 100644
--- a/console/android/src/main/AndroidManifest.xml
+++ b/console/android/src/main/AndroidManifest.xml
@@ -57,13 +57,20 @@
</intent-filter>
</service>
+ <receiver android:name=".service.GeofenceBootCompleteReceiver">
+ <intent-filter>
+ <action android:name="android.intent.action.BOOT_COMPLETED"/>
+ </intent-filter>
+ </receiver>
+
<receiver
android:name=".service.GeofenceTransitionsIntentService"
android:enabled="true"
android:exported="true"/>
- <service
- android:name=".service.GeofenceProvider$LocationService"
- android:exported="false"/>
+
+ <!--<service -->
+ <!--android:name=".service.GeofenceProvider$LocationService"-->
+ <!--android:exported="false"/>-->
</application>
diff --git a/console/android/src/main/java/org/openremote/android/MainActivity.java b/console/android/src/main/java/org/openremote/android/MainActivity.java
index 935c616ec..89ae0a14a 100644
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ b/console/android/src/main/java/org/openremote/android/MainActivity.java
@@ -8,6 +8,7 @@ import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
+import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
@@ -44,6 +45,7 @@ import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.firebase.iid.FirebaseInstanceId;
+import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;
import org.openremote.android.service.GeofenceProvider;
@@ -78,20 +80,6 @@ public class MainActivity extends Activity {
}
};
- protected BroadcastReceiver actionReceiver = new BroadcastReceiver() {
- @Override
- public void onReceive(Context context, Intent intent) {
- if (intent.hasExtra("action")) {
- String action = intent.getStringExtra("action");
- switch (action) {
- case "GEOFENCE_REFRESH":
- geofenceProvider.refreshGeofences();
- break;
- }
- }
- }
- };
-
protected class ErrorViewHolder {
View errorView;
Button btnReload;
@@ -148,9 +136,11 @@ public class MainActivity extends Activity {
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
// Enable remote debugging of WebView from Chrome Debugger tools
- if (isRemoteDebuggingEnabled()) {
- LOG.info("Enabling remote debugging");
- WebView.setWebContentsDebuggingEnabled(true);
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
+ if (0 != (getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE)) {
+ LOG.info("Enabling remote debugging");
+ WebView.setWebContentsDebuggingEnabled(true);
+ }
}
setContentView(R.layout.activity_web);
@@ -169,8 +159,6 @@ public class MainActivity extends Activity {
openIntentUrl(getIntent());
errorViewHolder = new ErrorViewHolder(findViewById(R.id.errorView));
-
- registerReceiver(actionReceiver, new IntentFilter(ACTION_BROADCAST));
}
@Override
@@ -211,8 +199,6 @@ public class MainActivity extends Activity {
@Override
protected void onDestroy() {
- unregisterReceiver(actionReceiver);
-
super.onDestroy();
}
@@ -261,7 +247,7 @@ public class MainActivity extends Activity {
webView.addJavascriptInterface(webAppInterface, "MobileInterface");
WebSettings webSettings = webView.getSettings();
- webSettings.setJavaScriptEnabled(true);
+ webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
webSettings.setDomStorageEnabled(true);
webSettings.setDatabaseEnabled(true);
@@ -323,12 +309,11 @@ public class MainActivity extends Activity {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
- // Remote debugging sessions from Chrome trigger "ERR_CACHE_MISS" that don't hurt, but we should not redirect the view
- if (isRemoteDebuggingEnabled() && error.getErrorCode() == ERROR_UNKNOWN) {
+ // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
+ if ("net::ERR_CACHE_MISS".contentEquals(error.getDescription())) {
return;
}
- // Remote debugging session from Chrome wants to load about:blank and then fails with "ERROR_UNSUPPORTED_SCHEME", ignore
if (request.getUrl().toString().equals("about:blank") && error.getErrorCode() == ERROR_UNSUPPORTED_SCHEME) {
return;
}
@@ -400,21 +385,30 @@ public class MainActivity extends Activity {
}
} else if (requestCode == GeofenceProvider.Companion.getLocationReponseCode()) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
- try {
- Map<String, Object> enableData = geofenceProvider.enable(String.format("%s/%s",
- getString(R.string.OR_BASE_SERVER),
- getString(R.string.OR_REALM)),
- consoleId);
- final String jsonString = new ObjectMapper().writeValueAsString(enableData);
- this.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- webView.evaluateJavascript(String.format("openremote.INSTANCE.console.handleProviderResponse('%s')", jsonString), null);
- }
- });
- } catch (Exception e) {
- e.printStackTrace();
- }
+
+ geofenceProvider.enable(MainActivity.this,
+ String.format("%s/%s",
+ getString(R.string.OR_BASE_SERVER),
+ getString(R.string.OR_REALM)),
+ consoleId,
+ new GeofenceProvider.EnableCallback() {
+ @Override
+ public void accept(@NotNull Map<String, ?> responseData) {
+ try {
+ final String jsonString = new ObjectMapper().writeValueAsString(responseData);
+ MainActivity.this.runOnUiThread(new Runnable() {
+ @Override
+ public void run() {
+ webView.evaluateJavascript(String.format(
+ "openremote.INSTANCE.console.handleProviderResponse('%s')",
+ jsonString), null);
+ }
+ });
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
+ });
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
@@ -478,8 +472,11 @@ public class MainActivity extends Activity {
}
protected void handleGeofenceProviderMessage(String action, JSONObject data) throws JSONException {
- if (action.equalsIgnoreCase("PROVIDER_INIT")) {
+ if (geofenceProvider == null) {
geofenceProvider = new GeofenceProvider(activity);
+ }
+
+ if (action.equalsIgnoreCase("PROVIDER_INIT")) {
Map<String, Object> initData = geofenceProvider.initialize();
notifyClient(initData);
} else if (action.equalsIgnoreCase("PROVIDER_ENABLE")) {
@@ -487,11 +484,16 @@ public class MainActivity extends Activity {
String consoleId = data.getString("consoleId");
if (consoleId != null) {
((MainActivity) activity).consoleId = consoleId;
- Map<String, Object> enableData = geofenceProvider.enable(String.format("%s/%s",
- getString(R.string.OR_BASE_SERVER),
- getString(R.string.OR_REALM)),
- consoleId);
- notifyClient(enableData);
+ geofenceProvider.enable(MainActivity.this, String.format("%s/%s",
+ getString(R.string.OR_BASE_SERVER),
+ getString(R.string.OR_REALM)),
+ consoleId, new GeofenceProvider.EnableCallback() {
+ @Override
+ public void accept(@NotNull Map<String, ?> responseData) {
+ //noinspection unchecked
+ notifyClient((Map<String, Object>) responseData);
+ }
+ });
}
}
} else if (action.equalsIgnoreCase("PROVIDER_DISABLE")) {
@@ -583,10 +585,6 @@ public class MainActivity extends Activity {
onConnectivityChanged(activeNetwork != null && activeNetwork.isConnectedOrConnecting());
}
}
-
- protected boolean isRemoteDebuggingEnabled() {
- return Boolean.valueOf(getString(R.string.ENABLE_REMOTE_DEBUGGING));
- }
}
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
index f43fe52fb..ebc7845a1 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -18,6 +18,7 @@ import com.google.firebase.messaging.RemoteMessage;
import org.openremote.android.service.AlertAction;
import org.openremote.android.service.AlertNotification;
+import org.openremote.android.service.GeofenceProvider;
import org.openremote.android.service.TokenService;
import java.util.logging.Level;
@@ -77,12 +78,20 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
} else if (remoteMessage.getData() != null && !remoteMessage.getData().isEmpty()) {
if (remoteMessage.getData().containsKey("action")) {
String action = remoteMessage.getData().get("action");
- Intent broadCastIntent = new Intent(MainActivity.ACTION_BROADCAST);
- broadCastIntent.putExtra("action", action);
- sendBroadcast(broadCastIntent);
+
+ switch (action) {
+ case "GEOFENCE_REFRESH":
+ GeofenceProvider geofenceProvider = new GeofenceProvider(getApplicationContext());
+ geofenceProvider.refreshGeofences();
+ break;
+ default:
+ Intent broadCastIntent = new Intent(MainActivity.ACTION_BROADCAST);
+ broadCastIntent.putExtra("action", action);
+ sendBroadcast(broadCastIntent);
+ break;
+ }
} else {
// Check if message contains a data payload with or-title or-body and actions
-
LOG.fine("Message data payload: " + remoteMessage.getData());
String title = remoteMessage.getData().get("or-title");
String body = remoteMessage.getData().get("or-body");
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt b/console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt
new file mode 100644
index 000000000..ed91f6df8
--- /dev/null
+++ b/console/android/src/main/java/org/openremote/android/service/GeofenceBootCompleteReceiver.kt
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2018, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This program is free software: you can redistribute it and/or modify
+ * it under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+package org.openremote.android.service
+
+import android.content.BroadcastReceiver
+import android.content.Context
+import android.content.Intent
+
+class GeofenceBootCompleteReceiver : BroadcastReceiver() {
+ override fun onReceive(context: Context?, intent: Intent?) {
+ if (context != null) {
+ GeofenceProvider.startGeofences(context)
+ }
+ }
+}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt b/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
index cfc575bac..4b0ff70cd 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
+++ b/console/android/src/main/java/org/openremote/android/service/GeofenceProvider.kt
@@ -2,79 +2,224 @@ package org.openremote.android.service
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
-import android.app.*
+import android.app.Activity
+import android.app.PendingIntent
import android.content.Context
-import android.content.Context.MODE_PRIVATE
import android.content.Intent
import android.content.pm.PackageManager
-import android.graphics.Color
-import android.os.Build
-import android.os.IBinder
-import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
-import android.support.v4.app.NotificationCompat
import android.support.v4.content.ContextCompat
import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
-import com.google.android.gms.location.*
-import org.openremote.android.BuildConfig
+import com.google.android.gms.location.Geofence
+import com.google.android.gms.location.GeofencingClient
+import com.google.android.gms.location.GeofencingRequest
+import com.google.android.gms.location.LocationServices
import org.openremote.android.R
-import java.io.*
import java.net.URL
+class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissionsResultCallback {
-class GeofenceProvider(val activity: Activity) {
+ interface EnableCallback {
+ fun accept(responseData: Map<String, Any>)
+ }
+
+ class GeofenceDefinition {
+ lateinit var id: String
+ var lat: Double = 0.0
+ var lng: Double = 0.0
+ var radius: Float = 0.0F
+ lateinit var httpMethod: String
+ lateinit var url: String
+ }
+
+// class LocationService : Service() {
+//
+// private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
+// private lateinit var locationCallback: LocationCallback
+//
+// override fun onCreate() {
+// super.onCreate()
+//
+// fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(applicationContext)
+//
+// locationCallback = object : LocationCallback() {
+// override fun onLocationResult(locationResult: LocationResult?) {
+// locationResult ?: return
+// Log.i("GeofenceProvider", "Location received: lat${locationResult.lastLocation.latitude}/lng${locationResult.lastLocation.longitude}")
+// }
+// }
+// }
+//
+// @SuppressLint("MissingPermission", "NewApi")
+// override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
+//
+// val notificationBuilder = when {
+// Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
+// val channelId = createNotificationChannel()
+// NotificationCompat.Builder(this, channelId)
+// }
+// else -> {
+// NotificationCompat.Builder(this)
+// }
+// }
+//
+// val notification = notificationBuilder.setOngoing(true)
+// .setSmallIcon(R.drawable.ic_notification)
+// .setCategory(Notification.CATEGORY_SERVICE)
+// .setContentTitle("Tracking location")
+// .build()
+//
+// notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_FOREGROUND_SERVICE or Notification.FLAG_NO_CLEAR
+//
+// //Force location updates
+// val locationRequest = LocationRequest().apply {
+// interval = 60000//1min
+// fastestInterval = 10000//10sec
+// priority = LocationRequest.PRIORITY_HIGH_ACCURACY
+// }
+//
+// fusedLocationProviderClient.requestLocationUpdates(locationRequest,
+// locationCallback,
+// null)
+//
+// startForeground(101, notification)
+//
+// return START_REDELIVER_INTENT
+// }
+//
+// override fun onDestroy() {
+// fusedLocationProviderClient.removeLocationUpdates(locationCallback)
+//
+// super.onDestroy()
+// }
+//
+// override fun onBind(intent: Intent?): IBinder? {
+// return null
+// }
+//
+// @RequiresApi(Build.VERSION_CODES.O)
+// private fun createNotificationChannel(): String {
+// val channelId = "${BuildConfig.APPLICATION_ID}.OREindhovenLocationService"
+// val channelName = "OR Eindhoven Location Service"
+// val channel = NotificationChannel(channelId,
+// channelName, NotificationManager.IMPORTANCE_LOW)
+// channel.lightColor = Color.BLUE
+// channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
+// channel.setShowBadge(false)
+// val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
+// service!!.createNotificationChannel(channel)
+// return channelId
+// }
+// }
companion object {
val baseUrlKey = "baseUrl"
val consoleIdKey = "consoleId"
- val geoPostUrlsKey = "geoPostUrls"
- var geoPostUrls = hashMapOf<String, List<String>>()
+ val geofencesKey = "geofences"
var locationReponseCode = 101
+ var JSON = ObjectMapper()
lateinit var consoleId: String
+
+ fun getGeofences(context: Context): Array<GeofenceDefinition> {
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+ val existingGeofencesJson = sharedPreferences.getString(geofencesKey, null)
+ if (existingGeofencesJson != null) {
+ return JSON.readValue(existingGeofencesJson, Array<GeofenceDefinition>::class.java)
+ } else {
+ return arrayOf()
+ }
+ }
+
+ fun startGeofences(context: Context) {
+ val geofences = getGeofences(context)
+ val baseUrl = getBaseUrl(context)
+ if (geofences.isEmpty() || baseUrl == null) {
+ return
+ }
+
+ Log.i("GeofenceProvider", "Starting geofences count=${geofences.size}")
+ val intent = getGeofencePendingIntent(context, baseUrl)
+ val geofencingClient = LocationServices.getGeofencingClient(context)
+
+ geofences.forEach {
+ addGeofence(geofencingClient, intent, it)
+ }
+ }
+
+
+ @SuppressLint("MissingPermission")
+ private fun addGeofence(geofencingClient: GeofencingClient, geofencePendingIntent: PendingIntent, geofenceDefinition: GeofenceDefinition) {
+ val geofence = Geofence.Builder()
+ .setRequestId(geofenceDefinition.id)
+ .setCircularRegion(geofenceDefinition.lat, geofenceDefinition.lng, geofenceDefinition.radius)
+ .setExpirationDuration(Geofence.NEVER_EXPIRE)
+ .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
+ .build()
+
+ val geofencingRequest = GeofencingRequest.Builder()
+ .addGeofence(geofence)
+ .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
+ .build()
+
+ geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent).run {
+ addOnSuccessListener {
+ Log.i("GeofenceProvider", "Geofence added: lat${geofenceDefinition.lat}/lng${geofenceDefinition.lng}/rad${geofenceDefinition.radius}")
+ }
+
+ addOnFailureListener { exception ->
+ Log.e("GeofenceProvider", "Failed to add geofence", exception)
+ }
+ }
+ }
+
+ private fun getGeofencePendingIntent(context: Context, baseURL: String): PendingIntent {
+ val intent = Intent(context, GeofenceTransitionsIntentService::class.java)
+ intent.putExtra(baseUrlKey, baseURL)
+ // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
+ // addGeofences() and removeGeofences().
+ return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
+ }
+
+ private fun getBaseUrl(context: Context): String? {
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+ return sharedPreferences.getString(baseUrlKey, null)
+ }
}
val version = "ORConsole"
val geofenceFetchEndpoint = "rules/geofences/"
- val sharedPreferences = activity.getSharedPreferences(activity.getString(R.string.app_name), Context.MODE_PRIVATE)
+ private val geofencingClient: GeofencingClient by lazy {
+ LocationServices.getGeofencingClient(context)
+ }
- lateinit var geofencingClient: GeofencingClient
- private val geofencePendingIntent: PendingIntent by lazy {
- val intent = Intent(activity, GeofenceTransitionsIntentService::class.java)
- intent.putExtra(baseUrlKey, baseURL)
- // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
- // addGeofences() and removeGeofences().
- PendingIntent.getBroadcast(activity, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
+ val geoPostUrls: Map<String, List<String>> by lazy {
+
+ hashMapOf(
+ "a" to arrayListOf("")
+ )
}
var baseURL: String? = null
var consoleId: String? = null
+ var enableCallback: EnableCallback? = null
fun initialize(): Map<String, Any> {
- var inputStream: ObjectInputStream? = null
- try {
- val file = File(activity.getDir("data", MODE_PRIVATE), geoPostUrlsKey)
- inputStream = ObjectInputStream(FileInputStream(file))
- geoPostUrls = inputStream.readObject() as? HashMap<String, List<String>> ?: hashMapOf()
- } catch (e: Exception) {
- geoPostUrls = hashMapOf()
- } finally {
- inputStream?.close()
- }
-
return hashMapOf(
"action" to "PROVIDER_INIT",
"provider" to "geofence",
"version" to version,
"requiresPermission" to true,
- "hasPermission" to checkPermission(),
+ "hasPermission" to (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED),
"success" to true
)
}
@SuppressLint("MissingPermission")
- fun enable(baseUrl: String, consoleId: String): Map<String, Any> {
+ fun enable(activity: Activity, baseUrl: String, consoleId: String, callback: EnableCallback) {
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+
baseURL = baseUrl
this.consoleId = consoleId
@@ -83,207 +228,116 @@ class GeofenceProvider(val activity: Activity) {
.putString(consoleIdKey, this.consoleId)
.apply()
- if(!checkPermission()) {
- registerPermissions()
- } else {
- geofencingClient = LocationServices.getGeofencingClient(activity)
-
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
- activity.startForegroundService(Intent(activity, LocationService::class.java))
- } else {
- activity.startService(Intent(activity, LocationService::class.java))
- }
-
- fetchGeofences()
+ if(ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ enableCallback = callback
+ registerPermissions(activity)
+ return
}
- return hashMapOf(
- "action" to "PROVIDER_ENABLE",
- "provider" to "geofence",
- "hasPermission" to checkPermission(),
- "success" to true
- )
+ return onEnable(callback)
}
fun disable() {
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+
+ removeGeofences(getGeofences(context))
+
sharedPreferences.edit()
.remove(baseUrlKey)
.remove(consoleIdKey)
+ .remove(geofencesKey)
.apply()
+
baseURL = null
consoleId = null
- activity.stopService(Intent(activity, LocationService::class.java))
- clearAllRegions()
- }
-
- fun checkPermission(): Boolean {
- // Ask for permission if it wasn't granted yet
- return ContextCompat.checkSelfPermission(activity, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
+ //context.stopService(Intent(context, LocationService::class.java))
}
- fun registerPermissions() {
- val permissions = arrayOf(ACCESS_FINE_LOCATION)
- ActivityCompat.requestPermissions(activity, permissions, locationReponseCode)
+ fun refreshGeofences() {
+ Log.i("GeofenceProvider", "refreshGeofences")
+ onEnable(null)
}
+ private fun onEnable(callback: EnableCallback?) {
+ Thread {
+ if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
+// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
+// context.startForegroundService(Intent(context, LocationService::class.java))
+// } else {
+// context.startService(Intent(context, LocationService::class.java))
+// }
- @SuppressLint("MissingPermission")
- fun addGeofence(geofenceDefinition: GeofenceDefinition) {
- val geofence = Geofence.Builder()
- .setRequestId(geofenceDefinition.id)
- .setCircularRegion(geofenceDefinition.lat, geofenceDefinition.lng, geofenceDefinition.radius)
- .setExpirationDuration(Geofence.NEVER_EXPIRE)
- .setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
- .build()
-
- val geofencingRequest = GeofencingRequest.Builder()
- .addGeofence(geofence)
- .setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER)
- .build()
-
- geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent).run {
- addOnSuccessListener {
- Log.i("GeofenceProvider", "Geofence added: lat${geofenceDefinition.lat}/lng${geofenceDefinition.lng}/rad${geofenceDefinition.radius}")
- geoPostUrls.put(geofenceDefinition.id, listOf(geofenceDefinition.httpMethod, geofenceDefinition.url))
+ fetchGeofences()
}
- addOnFailureListener { exception ->
- Log.e("GeofenceProvider", exception.message, exception)
- }
- }
+ callback?.accept(hashMapOf(
+ "action" to "PROVIDER_ENABLE",
+ "provider" to "geofence",
+ "hasPermission" to (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED),
+ "success" to true
+ ))
+ }.start()
}
- fun removeGeofence(id: String) {
- geofencingClient.removeGeofences(listOf(id)).run {
- addOnSuccessListener {
- geoPostUrls.remove(id)
- }
- }
+ private fun registerPermissions(activity: Activity) {
+ val permissions = arrayOf(ACCESS_FINE_LOCATION)
+ ActivityCompat.requestPermissions(activity, permissions, locationReponseCode)
}
- fun clearAllRegions() {
- if (geoPostUrls.keys.any()) {
- geofencingClient.removeGeofences(geoPostUrls.keys.toList()).run {
- addOnSuccessListener {
- Log.i("GeofenceProvider", "Geofences removed")
- }
-
- addOnFailureListener { exception ->
- Log.e("GeofenceProvider", exception.message, exception)
- }
- }
+ override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
+ if (enableCallback != null) {
+ onEnable(enableCallback!!)
+ enableCallback = null
}
- geoPostUrls = hashMapOf()
}
- fun refreshGeofences() {
- Thread({
- fetchGeofences()
- }).start()
- }
+ private fun fetchGeofences() {
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+ val geofencesJson = URL("$baseURL/$geofenceFetchEndpoint$consoleId").readText()
+ val geofences = JSON.readValue(geofencesJson, Array<GeofenceDefinition>::class.java)
+ val baseUrl = baseURL.orEmpty()
+ removeGeofences(getGeofences(context))
+
+ Log.i("GeofenceProvider", "fetchGeofences: count=${geofences.size}")
- protected fun fetchGeofences() {
- val response = URL("$baseURL/$geofenceFetchEndpoint$consoleId").readText()
- val geofences = ObjectMapper().readValue(response, Array<GeofenceDefinition>::class.java)
- clearAllRegions()
- Log.i("fetchGeofences", "${geofences.size} geofences")
geofences.forEach {
- addGeofence(it)
- geoPostUrls[it.id] = listOf(it.httpMethod, it.url)
+ addGeofence(geofencingClient, getGeofencePendingIntent(context, baseUrl), it)
}
- val file = File(activity.getDir("data", MODE_PRIVATE), geoPostUrlsKey)
- val outputStream = ObjectOutputStream(FileOutputStream(file))
- outputStream.writeObject(geoPostUrls)
- outputStream.flush()
- outputStream.close()
- }
- class GeofenceDefinition {
- var id: String = ""
- var lat: Double = 0.0
- var lng: Double = 0.0
- var radius: Float = 0.0F
- var httpMethod: String = ""
- var url: String = ""
+ sharedPreferences.edit()
+ .putString(geofencesKey, geofencesJson)
+ .apply()
}
- class LocationService : Service() {
-
- private lateinit var fusedLocationProviderClient: FusedLocationProviderClient
- private lateinit var locationCallback: LocationCallback
-
- override fun onCreate() {
- super.onCreate()
-
- fusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(applicationContext)
-
- locationCallback = object : LocationCallback() {
- override fun onLocationResult(locationResult: LocationResult?) {
- locationResult ?: return
- Log.i("GeofenceProvider", "Location received: lat${locationResult.lastLocation.latitude}/lng${locationResult.lastLocation.longitude}")
- }
- }
- }
-
- @SuppressLint("MissingPermission")
- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
-
- val notificationBuilder = when {
- Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
- val channelId = createNotificationChannel()
- NotificationCompat.Builder(this, channelId)
- }
- else -> {
- NotificationCompat.Builder(this)
- }
+ private fun removeGeofence(id: String) {
+ geofencingClient.removeGeofences(listOf(id)).run {
+ addOnSuccessListener {
+ Log.i("GeofenceProvider", "Geofence removed: $id")
}
- val notification = notificationBuilder.setOngoing(true)
- .setSmallIcon(R.drawable.ic_notification)
- .setCategory(Notification.CATEGORY_SERVICE)
- .setContentTitle("Tracking location")
- .build()
-
- notification.flags = notification.flags or Notification.FLAG_ONGOING_EVENT or Notification.FLAG_FOREGROUND_SERVICE or Notification.FLAG_NO_CLEAR
-
- //Force location updates
- val locationRequest = LocationRequest().apply {
- interval = 60000//1min
- fastestInterval = 10000//10sec
- priority = LocationRequest.PRIORITY_HIGH_ACCURACY
+ addOnFailureListener { exception ->
+ Log.e("GeofenceProvider", "Failed to remove geofence", exception)
}
-
- fusedLocationProviderClient.requestLocationUpdates(locationRequest,
- locationCallback,
- null)
-
- startForeground(101, notification)
-
- return START_REDELIVER_INTENT
}
+ }
- override fun onDestroy() {
- fusedLocationProviderClient.removeLocationUpdates(locationCallback)
+ private fun removeGeofences(geofences: Array<GeofenceDefinition>) {
+ removeGeofences(geofences.map { it.id })
+ }
- super.onDestroy()
+ private fun removeGeofences(ids: List<String>) {
+ if (ids.isEmpty()) {
+ return
}
- override fun onBind(intent: Intent?): IBinder? {
- return null
- }
+ geofencingClient.removeGeofences(ids).run {
+ addOnSuccessListener {
+ Log.i("GeofenceProvider", "Geofences removed")
+ }
- @RequiresApi(Build.VERSION_CODES.O)
- private fun createNotificationChannel(): String {
- val channelId = "${BuildConfig.APPLICATION_ID}.OREindhovenLocationService"
- val channelName = "OR Eindhoven Location Service"
- val channel = NotificationChannel(channelId,
- channelName, NotificationManager.IMPORTANCE_LOW)
- channel.lightColor = Color.BLUE
- channel.lockscreenVisibility = Notification.VISIBILITY_PRIVATE
- channel.setShowBadge(false)
- val service = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager?
- service!!.createNotificationChannel(channel)
- return channelId
+ addOnFailureListener { exception ->
+ Log.e("GeofenceProvider", exception.message, exception)
+ }
}
}
}
\ No newline at end of file
diff --git a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt b/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
index 815ddafd3..6b1ff73a8 100644
--- a/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
+++ b/console/android/src/main/java/org/openremote/android/service/GeofenceTransitionsIntentService.kt
@@ -9,6 +9,7 @@ import com.google.android.gms.location.Geofence
import com.google.android.gms.location.GeofencingEvent
import java.net.HttpURLConnection
import java.net.URL
+import java.util.logging.Level
import java.util.logging.Logger
class GeofenceTransitionsIntentService : BroadcastReceiver() {
@@ -19,7 +20,7 @@ class GeofenceTransitionsIntentService : BroadcastReceiver() {
val geofencingEvent = GeofencingEvent.fromIntent(intent)
if (geofencingEvent.hasError()) {
- Log.w("Geofence", "Error handling geofence event")
+ LOG.warning("Error handling geofence event")
return
}
@@ -27,46 +28,56 @@ class GeofenceTransitionsIntentService : BroadcastReceiver() {
val baseUrl = intent!!.getStringExtra(GeofenceProvider.baseUrlKey)
val geofenceTransition = geofencingEvent.geofenceTransition
- val geofence = geofencingEvent.triggeringGeofences.first()
- GeofenceProvider.geoPostUrls[geofence.requestId]?.let { data ->
+ val geofenceDefinitions = GeofenceProvider.getGeofences(context!!)
- val url = URL("$baseUrl${data[1]}")
- val connection = url.openConnection() as HttpURLConnection
- connection.setRequestProperty("Content-Type", "application/json")
- connection.requestMethod = data[0]
- connection.connectTimeout = 10000
- connection.doInput = false
+ if (geofenceDefinitions.isEmpty()) {
+ LOG.fine("No stored geofence definitions so ignoring triggered geofence")
+ return
+ }
- val postJson = when (geofenceTransition) {
- Geofence.GEOFENCE_TRANSITION_ENTER -> {
- hashMapOf(
- "type" to "Point",
- "coordinates" to arrayOf(geofencingEvent.triggeringLocation.longitude, geofencingEvent.triggeringLocation.latitude)
- )
- }
- else -> {
- null
- }
- }
+ geofencingEvent.triggeringGeofences.forEach {
+ geofence ->
+ val geofenceDefinition = geofenceDefinitions.firstOrNull { it.id == geofence.requestId }
- Thread({
- try {
- connection.doOutput = true
- connection.setChunkedStreamingMode(0)
- connection.outputStream
- ObjectMapper().writeValue(connection.outputStream, postJson)
+ if (geofenceDefinition != null) {
+ val url = URL("$baseUrl${geofenceDefinition.url}")
+ val connection = url.openConnection() as HttpURLConnection
+ connection.setRequestProperty("Content-Type", "application/json")
+ connection.requestMethod = geofenceDefinition.httpMethod
+ connection.connectTimeout = 10000
+ connection.doInput = false
- connection.outputStream.flush()
- val responseCode = connection.responseCode
- Log.i("Geofence", "Location posted to server: response=" + responseCode)
+ val postJson = when (geofenceTransition) {
+ Geofence.GEOFENCE_TRANSITION_ENTER -> {
+ hashMapOf(
+ "type" to "Point",
+ "coordinates" to arrayOf(geofencingEvent.triggeringLocation.longitude, geofencingEvent.triggeringLocation.latitude)
+ )
+ }
+ else -> {
+ null
+ }
+ }
- } catch (exception: Exception) {
- Log.e("Geofence", exception.message, exception)
- print(exception)
- } finally {
- connection.disconnect()
+ Thread {
+ try {
+ connection.doOutput = true
+ connection.setChunkedStreamingMode(0)
+ connection.outputStream
+ ObjectMapper().writeValue(connection.outputStream, postJson)
+
+ connection.outputStream.flush()
+ val responseCode = connection.responseCode
+ LOG.info("Location posted to server: response=" + responseCode)
+
+ } catch (exception: Exception) {
+ LOG.log(Level.SEVERE, exception.message, exception)
+ print(exception)
+ } finally {
+ connection.disconnect()
+ }
+ }.start()
}
- }).start()
- }
+ }
}
}
\ No newline at end of file
diff --git a/console/android/src/main/res/values/strings.xml b/console/android/src/main/res/values/strings.xml
index 4e4f40979..4915389c4 100644
--- a/console/android/src/main/res/values/strings.xml
+++ b/console/android/src/main/res/values/strings.xml
@@ -3,7 +3,6 @@
<string name="WEBSITE_URL">http://www.openremote.com/</string>
<string name="OR_BASE_SERVER">http://192.168.0.143:8080</string>
<string name="OR_CONSOLE_URL">/console/REALM/index.html</string>
- <string name="ENABLE_REMOTE_DEBUGGING">false</string>
<string name="SHARED_PREF_REFRESH_TOKEN">REFRESH_TOKEN</string>
<string name="OR_REALM">REALM</string>
<string name="SHARED_PREF_FCM_TOKEN">FCM_TOKEN_KEY</string>