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

Rich Turner4b517e016a3e
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 653b14712..8e6a9f568 100644
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ b/console/android/src/main/java/org/openremote/android/MainActivity.java
@@ -59,7 +59,8 @@ public class MainActivity extends Activity {
private static final Logger LOG = Logger.getLogger(MainActivity.class.getName());
- private final int WRITE_PERMISSION_REQUEST = 999;
+ private final int WRITE_PERMISSION_FOR_DOWNLOAD = 999;
+ private final int WRITE_PERMISSION_FOR_LOGGING = 1000;
public static final String ACTION_BROADCAST = "ACTION_BROADCAST";
@@ -131,6 +132,19 @@ public class MainActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
+ if (Boolean.parseBoolean(getApplicationContext().getString(R.string.DEBUG_LOGGING))) {
+ // Check write permission for logging purposes
+
+ String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
+ if (ContextCompat.checkSelfPermission(getApplicationContext(), writePermission) != PackageManager.PERMISSION_GRANTED) {
+ // Write permission has not been granted yet, request it.
+ ActivityCompat.requestPermissions(this, new String[]{writePermission}, WRITE_PERMISSION_FOR_LOGGING);
+ } else {
+ // Assume logging has already been initialised by main application
+ }
+ }
+
+
context = this;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
@@ -345,8 +359,8 @@ public class MainActivity extends Activity {
String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
if (ContextCompat.checkSelfPermission(context, writePermission) != PackageManager.PERMISSION_GRANTED) {
- // Location permission has not been granted yet, request it.
- ActivityCompat.requestPermissions((MainActivity) context, new String[]{writePermission}, WRITE_PERMISSION_REQUEST);
+ // Write permission has not been granted yet, request it.
+ ActivityCompat.requestPermissions((MainActivity) context, new String[]{writePermission}, WRITE_PERMISSION_FOR_DOWNLOAD);
} else {
DownloadManager.Request request = new
DownloadManager.Request(Uri.parse(url));
@@ -376,7 +390,12 @@ public class MainActivity extends Activity {
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
- if (requestCode == WRITE_PERMISSION_REQUEST) {
+ if (requestCode == WRITE_PERMISSION_FOR_LOGGING) {
+ if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
+ // Add File logging
+ MainApplication.addFileHandler(this);
+ }
+ } else if (requestCode == WRITE_PERMISSION_FOR_DOWNLOAD) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), R.string.downloading_file, Toast.LENGTH_LONG).show();
}
diff --git a/console/android/src/main/java/org/openremote/android/MainApplication.java b/console/android/src/main/java/org/openremote/android/MainApplication.java
index 7903b081c..177f2f019 100644
--- a/console/android/src/main/java/org/openremote/android/MainApplication.java
+++ b/console/android/src/main/java/org/openremote/android/MainApplication.java
@@ -1,9 +1,20 @@
package org.openremote.android;
+import android.Manifest;
import android.app.Application;
+import android.content.Context;
+import android.content.Intent;
+import android.content.pm.PackageManager;
+import android.media.MediaScannerConnection;
+import android.net.Uri;
+import android.os.Environment;
+import android.support.v4.app.ActivityCompat;
+import android.support.v4.content.ContextCompat;
-import java.util.logging.Level;
-import java.util.logging.Logger;
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.PrintWriter;
+import java.util.logging.*;
public class MainApplication extends Application {
@@ -13,11 +24,49 @@ public class MainApplication extends Application {
// Fix and configure JUL
AndroidLoggingHandler.reset(new AndroidLoggingHandler());
+
if (Boolean.parseBoolean(getApplicationContext().getString(R.string.DEBUG_LOGGING))) {
java.util.logging.Logger.getLogger("org.openremote").setLevel(Level.FINEST);
+
+ // Get write permission
+ String writePermission = Manifest.permission.WRITE_EXTERNAL_STORAGE;
+ if (ContextCompat.checkSelfPermission(getApplicationContext(), writePermission) == PackageManager.PERMISSION_GRANTED) {
+ addFileHandler(getApplicationContext());
+ }
}
Logger LOG = Logger.getLogger(MainApplication.class.getName());
LOG.info(">>> Starting OpenRemote application");
}
+
+ static void addFileHandler(Context context) {
+
+ try {
+
+ File logDirectory = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "openremote");
+
+ if (!logDirectory.exists() && !logDirectory.mkdirs()) {
+ throw new Exception("Failed to make log directory");
+ }
+
+ String logFilePattern = logDirectory.getAbsolutePath() + File.separator + "openremote.log";
+
+ FileHandler fileHandler = null;
+ fileHandler = new FileHandler(logFilePattern, 10000000, 10, true);
+ fileHandler.setFormatter(new SimpleFormatter());
+ Logger rootLogger = LogManager.getLogManager().getLogger("");
+ rootLogger.addHandler(fileHandler);
+
+ rootLogger.info("Added logging file handler");
+
+ // Force scan of first log file as might not show via MTP otherwise
+ MediaScannerConnection.scanFile(
+ context,
+ new String[]{logFilePattern + ".0"},
+ null,
+ null);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+ }
}
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 3176888e7..675f4f27e 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -181,7 +181,7 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
}
}
- LOG.fine("Showing notification (" + (buttons != null ? buttons.length + " buttons): " : "") + body);
+ LOG.fine("Showing notification id=" + notificationId + ", title=" + title + ", body=" + body + ", action=" + action + ", buttons=" +(buttons != null ? buttons.length : 0));
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
diff --git a/console/android/src/main/java/org/openremote/android/service/AlertNotification.java b/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
deleted file mode 100644
index c7c3d2108..000000000
--- a/console/android/src/main/java/org/openremote/android/service/AlertNotification.java
+++ /dev/null
@@ -1,109 +0,0 @@
-package org.openremote.android.service;
-
-
-import java.io.Serializable;
-import java.util.Date;
-import java.util.List;
-
-public class AlertNotification implements Serializable {
- private Long id;
-
- private String title;
-
- private Date createdOn;
-
- private String message;
-
- private List<AlertAction> actions;
-
- private String appUrl;
-
- private String userId;
-
- private DeliveryStatus deliveryStatus;
-
- public Long getId() {
- return id;
- }
-
- public void setId(Long id) {
- this.id = id;
- }
-
- public String getTitle() {
- return title;
- }
-
- public void setTitle(String title) {
- this.title = title;
- }
-
- public Date getCreatedOn() {
- return createdOn;
- }
-
- public void setCreatedOn(Date createdOn) {
- this.createdOn = createdOn;
- }
-
- public String getMessage() {
- return message;
- }
-
- public void setMessage(String message) {
- this.message = message;
- }
-
- public List<AlertAction> getActions() {
- return actions;
- }
-
- public void setActions(List<AlertAction> actions) {
- this.actions = actions;
- }
-
- public String getAppUrl() {
- return appUrl;
- }
-
- public void setAppUrl(String appUrl) {
- this.appUrl = appUrl;
- }
-
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- public DeliveryStatus getDeliveryStatus() {
- return deliveryStatus;
- }
-
- public void setDeliveryStatus(DeliveryStatus deliveryStatus) {
- this.deliveryStatus = deliveryStatus;
- }
-
- @Override
- public String toString() {
- return "AlertNotification{" +
- "id=" + id +
- ", title='" + title + '\'' +
- ", createdOn='" + createdOn + '\'' +
- ", message='" + message + '\'' +
- ", actions=" + actions +
- ", appUrl='" + appUrl + '\'' +
- ", userId='" + userId + '\'' +
- ", deliveryStatus=" + deliveryStatus +
- '}';
- }
-
-
-
- public enum ActionType {
- ACTUATOR,
- LINK
- }
-}
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 5dc4f85ff..78e37fb9a 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
@@ -16,6 +16,7 @@ import com.google.android.gms.location.GeofencingRequest
import com.google.android.gms.location.LocationServices
import org.openremote.android.R
import java.net.URL
+import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
@@ -32,6 +33,10 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
var radius: Float = 0.0F
lateinit var httpMethod: String
lateinit var url: String
+
+ override fun toString(): String {
+ return "GeofenceDefinition(id='$id', lat=$lat, lng=$lng, radius=$radius, httpMethod='$httpMethod', url='$url')"
+ }
}
// class LocationService : Service() {
@@ -156,12 +161,13 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
@SuppressLint("MissingPermission")
private fun addGeofence(geofencingClient: GeofencingClient, geofencePendingIntent: PendingIntent, geofenceDefinition: GeofenceDefinition) {
- LOG.info("Adding geofence: id=${geofenceDefinition.id} lat=${geofenceDefinition.lat} lng=${geofenceDefinition.lng}, radius=${geofenceDefinition.radius}")
+ LOG.info("Adding geofence: $geofenceDefinition")
val geofence = Geofence.Builder()
.setRequestId(geofenceDefinition.id)
.setCircularRegion(geofenceDefinition.lat, geofenceDefinition.lng, geofenceDefinition.radius)
.setExpirationDuration(Geofence.NEVER_EXPIRE)
+ .setNotificationResponsiveness(5000)
.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER or Geofence.GEOFENCE_TRANSITION_EXIT)
.build()
@@ -172,11 +178,11 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
geofencingClient.addGeofences(geofencingRequest, geofencePendingIntent).run {
addOnSuccessListener {
- LOG.info("Added geofence")
+ LOG.info("Added geofence: ${geofenceDefinition.id}")
}
addOnFailureListener { exception ->
- LOG.log(Level.SEVERE, "Add geofence failed", exception)
+ LOG.log(Level.SEVERE, "Add geofence failed: ${geofenceDefinition.id}", exception)
}
}
}
@@ -254,7 +260,39 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
fun refreshGeofences() {
LOG.info("Refresh geofences")
- onEnable(null)
+
+ val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
+ val url = "${getBaseUrl(context)}/$geofenceFetchEndpoint${getConsoleId(context)}"
+ LOG.info("Fetching geofences from server: ${url}")
+
+ val geofencesJson = URL(url).readText()
+ val geofences = JSON.readValue(geofencesJson, Array<GeofenceDefinition>::class.java)
+
+ LOG.info("Fetched geofences=${geofences.size}")
+
+ // Remove previous fences that no longer exist
+ val oldFences = getGeofences(context)
+ val remainingFences : ArrayList<GeofenceProvider.GeofenceDefinition> = arrayListOf()
+
+ oldFences.forEach { oldFence ->
+ if (geofences.none { Objects.equals(it.id, oldFence.id)}) {
+ LOG.info("Geofence now obsolete: $oldFence")
+ removeGeofence(oldFence.id)
+ } else {
+ remainingFences.add(oldFence)
+ LOG.info("Geofence unchanged: $oldFence")
+ }
+ }
+
+ geofences.forEach { geofence ->
+ if (remainingFences.none { Objects.equals(it.id, geofence.id)}) {
+ addGeofence(geofencingClient, getGeofencePendingIntent(context, getBaseUrl(context).orEmpty()), geofence)
+ }
+ }
+
+ sharedPreferences.edit()
+ .putString(geofencesKey, geofencesJson)
+ .apply()
}
private fun onEnable(callback: EnableCallback?) {
@@ -271,7 +309,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
// context.startService(Intent(context, LocationService::class.java))
// }
- fetchGeofences()
+ refreshGeofences()
}
callback?.accept(hashMapOf(
@@ -296,27 +334,6 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
}
}
- private fun fetchGeofences() {
- val sharedPreferences = context.getSharedPreferences(context.getString(R.string.app_name), Context.MODE_PRIVATE)
- val url = "${getBaseUrl(context)}/$geofenceFetchEndpoint${getConsoleId(context)}"
- LOG.info("Fetching geofences from server: ${url}")
-
- val geofencesJson = URL(url).readText()
- val geofences = JSON.readValue(geofencesJson, Array<GeofenceDefinition>::class.java)
-
- LOG.info("Fetched geofences=${geofences.size}")
-
- removeGeofences(getGeofences(context))
-
- geofences.forEach {
- addGeofence(geofencingClient, getGeofencePendingIntent(context, getBaseUrl(context).orEmpty()), it)
- }
-
- sharedPreferences.edit()
- .putString(geofencesKey, geofencesJson)
- .apply()
- }
-
private fun removeGeofence(id: String) {
geofencingClient.removeGeofences(listOf(id)).run {
addOnSuccessListener {
@@ -324,7 +341,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
}
addOnFailureListener { exception ->
- LOG.log(Level.SEVERE, "Failed to remove geofence", exception)
+ LOG.log(Level.SEVERE, "Failed to remove geofence: $id", exception)
}
}
}