Skip to content

armgit / core

Public Imported from GitHub
0

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

Updated to AndroidX Added GET_LOCATION action to GeofenceProvider

Michael Rademaker774c1084fe58
diff --git a/console/android/build.gradle b/console/android/build.gradle
index 6bbfabb62..356e18e62 100644
--- a/console/android/build.gradle
+++ b/console/android/build.gradle
@@ -1,5 +1,4 @@
buildscript {
- ext.kotlin_version = "$kotlinVersion"
repositories {
google()
jcenter()
@@ -59,10 +58,9 @@ android {
dependencies {
implementation "com.squareup.okhttp3:okhttp:$okhttp3Version"
implementation "com.squareup.retrofit2:retrofit:$retrofitVersion"
- implementation "com.android.support:support-compat:$androidSupportVersion"
- implementation "com.android.support:appcompat-v7:$androidSupportVersion"
- implementation "com.google.firebase:firebase-core:$fcmVersion"
- implementation "com.google.firebase:firebase-messaging:$fcmVersion"
+ implementation "androidx.core:core:1.0.2"
+ implementation "com.google.firebase:firebase-core:$firebaseCoreVersion"
+ implementation "com.google.firebase:firebase-messaging:$fcmMessagingVersion"
implementation "com.squareup.retrofit2:converter-jackson:$jacksonVersion"
implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion"
implementation "com.google.android.gms:play-services-location:$googlePlayVersion"
diff --git a/console/android/gradle.properties b/console/android/gradle.properties
index dd310b8ae..39316d8e7 100644
--- a/console/android/gradle.properties
+++ b/console/android/gradle.properties
@@ -3,19 +3,4 @@ org.gradle.jvmargs=-Xmx2g
projectVersion = 3.0-SNAPSHOT
# Increment this for every release
-projectVersionCode = 1
-
-# Android 5.0
-androidMinVersion = 21
-androidTargetVersion = 25
-
-kotlinVersion = 1.3.10
-androidGradleVersion = 3.4.0
-androidCompileVersion = 26
-androidSupportVersion = 26.1.0
-
-okhttp3Version = 3.6.0
-retrofitVersion = 2.2.0
-googlePlayVersion = 15.0.1
-fcmVersion = 15.0.2
-jacksonVersion = 2.2.0
\ No newline at end of file
+projectVersionCode = 1
\ No newline at end of file
diff --git a/console/android/src/main/AndroidManifest.xml b/console/android/src/main/AndroidManifest.xml
index 656bfab73..531bb5bff 100644
--- a/console/android/src/main/AndroidManifest.xml
+++ b/console/android/src/main/AndroidManifest.xml
@@ -42,13 +42,6 @@
</service>
- <service
- android:name="org.openremote.android.ORFirebaseInstanceIDService">
- <intent-filter>
- <action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
- </intent-filter>
- </service>
-
<receiver android:name=".service.GeofenceBootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
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 43ae4d6e7..c6740e01d 100644
--- a/console/android/src/main/java/org/openremote/android/MainActivity.java
+++ b/console/android/src/main/java/org/openremote/android/MainActivity.java
@@ -5,7 +5,11 @@ import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.DownloadManager;
-import android.content.*;
+import android.content.BroadcastReceiver;
+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.PackageInfo;
import android.content.pm.PackageManager;
@@ -14,21 +18,36 @@ import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.http.SslError;
-import android.os.*;
+import android.os.Build;
+import android.os.Bundle;
+import android.os.Environment;
+import android.os.Handler;
+import android.os.Looper;
import android.preference.PreferenceManager;
-import android.support.annotation.NonNull;
-import android.support.v4.app.ActivityCompat;
-import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
-import android.webkit.*;
+import android.webkit.ConsoleMessage;
+import android.webkit.CookieManager;
+import android.webkit.DownloadListener;
+import android.webkit.JavascriptInterface;
+import android.webkit.SslErrorHandler;
+import android.webkit.URLUtil;
+import android.webkit.WebChromeClient;
+import android.webkit.WebResourceError;
+import android.webkit.WebResourceRequest;
+import android.webkit.WebResourceResponse;
+import android.webkit.WebSettings;
+import android.webkit.WebView;
+import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
+
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;
@@ -41,6 +60,10 @@ import java.util.Objects;
import java.util.logging.Level;
import java.util.logging.Logger;
+import androidx.annotation.NonNull;
+import androidx.core.app.ActivityCompat;
+import androidx.core.content.ContextCompat;
+
public class MainActivity extends Activity {
private static final Logger LOG = Logger.getLogger(MainActivity.class.getName());
@@ -111,7 +134,7 @@ public class MainActivity extends Activity {
String platform = "Android " + Build.VERSION.RELEASE;
String name = getString(R.string.OR_CONSOLE_NAME);
String providers = getString(R.string.OR_CONSOLE_PROVIDERS);
- String version = "N/A";
+ String version = BuildConfig.VERSION_NAME;
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
@@ -121,10 +144,10 @@ public class MainActivity extends Activity {
}
return getString(R.string.OR_BASE_SERVER) + getString(R.string.OR_CONSOLE_URL)
- + "?consolePlatform=" + platform
- + "&consoleName=" + name
- + "&consoleVersion=" + version
- + "&consoleProviders=" + providers;
+ + "?consolePlatform=" + platform
+ + "&consoleName=" + name
+ + "&consoleVersion=" + version
+ + "&consoleProviders=" + providers;
}
@Override
@@ -185,7 +208,7 @@ public class MainActivity extends Activity {
protected void openIntentUrl(Intent intent) {
if (!intent.hasExtra("appUrl")) {
String url = getClientUrl();
- LOG.fine("Loading web view: " + url);
+ LOG.fine("Loading web view: " + url);
loadUrl(url);
} else {
String url = getClientUrl();
@@ -291,14 +314,14 @@ public class MainActivity extends Activity {
// server was reinstalled), we detect the failure and then don't show an error view. We clear the stored
// invalid token. The web app will then start a new login.
if (request.getUrl().getLastPathSegment() != null &&
- request.getUrl().getLastPathSegment().equals("token") &&
- request.getMethod().equals("POST") &&
- errorResponse.getStatusCode() == 400) {
- MainActivity.this.storeData(getString(R.string.SHARED_PREF_REFRESH_TOKEN), null);
- return;
- }
+ request.getUrl().getLastPathSegment().equals("token") &&
+ request.getMethod().equals("POST") &&
+ errorResponse.getStatusCode() == 400) {
+ MainActivity.this.storeData(getString(R.string.SHARED_PREF_REFRESH_TOKEN), null);
+ return;
+ }
- handleError(errorResponse.getStatusCode(), errorResponse.getReasonPhrase(), request.getUrl().toString(), request.isForMainFrame());
+ handleError(errorResponse.getStatusCode(), errorResponse.getReasonPhrase(), request.getUrl().toString(), request.isForMainFrame());
}
@Override
@@ -333,8 +356,8 @@ public class MainActivity extends Activity {
}
handleError(
- error.getErrorCode(), error.getDescription().toString(),
- request.getUrl().toString(), request.isForMainFrame());
+ error.getErrorCode(), error.getDescription().toString(),
+ request.getUrl().toString(), request.isForMainFrame());
}
@Override
@@ -378,8 +401,8 @@ public class MainActivity extends Activity {
//TODO should we always ignore image errors?
if (failingUrl != null && (failingUrl.endsWith("png")
- || failingUrl.endsWith("jpg")
- || failingUrl.endsWith("ico"))) {
+ || failingUrl.endsWith("jpg")
+ || failingUrl.endsWith("ico"))) {
LOG.info("Ignoring error loading image resource");
return;
}
@@ -418,7 +441,7 @@ public class MainActivity extends Activity {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{writePermission}, WRITE_PERMISSION_FOR_DOWNLOAD);
} else {
DownloadManager.Request request = new
- DownloadManager.Request(Uri.parse(url));
+ DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
//------------------------COOKIE!!------------------------
@@ -527,15 +550,15 @@ public class MainActivity extends Activity {
if (consoleId != null) {
((MainActivity) activity).consoleId = consoleId;
geofenceProvider.enable(MainActivity.this, String.format("%s/api/%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);
- }
- });
+ getString(R.string.OR_BASE_SERVER),
+ getString(R.string.OR_REALM)),
+ consoleId, new GeofenceProvider.GeofenceCallback() {
+ @Override
+ public void accept(@NotNull Map<String, ?> responseData) {
+ //noinspection unchecked
+ notifyClient((Map<String, Object>) responseData);
+ }
+ });
}
} else if (action.equalsIgnoreCase("PROVIDER_DISABLE")) {
geofenceProvider.disable();
@@ -545,6 +568,14 @@ public class MainActivity extends Activity {
notifyClient(response);
} else if (action.equalsIgnoreCase("GEOFENCE_REFRESH")) {
geofenceProvider.refreshGeofences();
+ } else if (action.equalsIgnoreCase("GET_LOCATION")) {
+ geofenceProvider.getLocation(MainActivity.this, new GeofenceProvider.GeofenceCallback() {
+ @Override
+ public void accept(@NotNull Map<String, ?> responseData) {
+ //noinspection unchecked
+ notifyClient((Map<String, Object>) responseData);
+ }
+ });
}
}
@@ -683,7 +714,7 @@ public class MainActivity extends Activity {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm
- = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
+ = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
onConnectivityChanged(activeNetwork != null && activeNetwork.isConnectedOrConnecting());
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 a97da7894..1848cecdd 100644
--- a/console/android/src/main/java/org/openremote/android/MainApplication.java
+++ b/console/android/src/main/java/org/openremote/android/MainApplication.java
@@ -6,7 +6,7 @@ import android.content.Context;
import android.content.pm.PackageManager;
import android.media.MediaScannerConnection;
import android.os.Environment;
-import android.support.v4.content.ContextCompat;
+import androidx.core.content.ContextCompat;
import java.io.File;
import java.util.logging.*;
diff --git a/console/android/src/main/java/org/openremote/android/ORFirebaseInstanceIDService.java b/console/android/src/main/java/org/openremote/android/ORFirebaseInstanceIDService.java
deleted file mode 100644
index ea7c97ff8..000000000
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseInstanceIDService.java
+++ /dev/null
@@ -1,59 +0,0 @@
-package org.openremote.android;
-
-import com.google.firebase.iid.FirebaseInstanceId;
-import com.google.firebase.iid.FirebaseInstanceIdService;
-import org.openremote.android.service.TokenService;
-
-import java.util.logging.Logger;
-
-
-/**
- * This runs only once when the application is started for the first time after install. To generate
- * new device tokens and send them to the server, uninstall the app first.
- */
-public class ORFirebaseInstanceIDService extends FirebaseInstanceIdService {
-
- private static final Logger LOG = Logger.getLogger(ORFirebaseInstanceIDService.class.getName());
-
- private TokenService tokenService;
-
- @Override
- public void onCreate() {
- super.onCreate();
- tokenService = new TokenService(getApplicationContext());
- }
-
- public ORFirebaseInstanceIDService() {
- }
-
- /**
- * Called if InstanceID token is updated. This may occur if the security of
- * the previous token had been compromised. Note that this is called when the InstanceID token
- * is initially generated so this is where you would retrieve the token.
- */
- // [START refresh_token]
- @Override
- public void onTokenRefresh() {
- // Get updated InstanceID token.
- String refreshedToken = FirebaseInstanceId.getInstance().getToken();
- LOG.fine("Obtained FCM token: " + refreshedToken);
-
- // If you want to send messages to this application instance or
- // manage this apps subscriptions on the server side, send the
- // Instance ID token to your app server.
- sendRegistrationToServer(refreshedToken, FirebaseInstanceId.getInstance().getId());
- }
- // [END refresh_token]
-
- /**
- * Persist token to third-party servers.
- * <p>
- * Modify this method to associate the user's FCM InstanceID token with any server-side account
- * maintained by your application.
- *
- * @param token The new token.
- */
- private void sendRegistrationToServer(final String token, final String id) {
- tokenService.sendOrStoreFCMToken(token, id);
- }
-}
\ No newline at end of file
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 25cfcf8f1..668f0ebbd 100644
--- a/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
+++ b/console/android/src/main/java/org/openremote/android/ORFirebaseMessagingService.java
@@ -10,10 +10,11 @@ import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
-import android.support.annotation.RequiresApi;
-import android.support.v4.app.NotificationCompat;
+import androidx.annotation.RequiresApi;
+import androidx.core.app.NotificationCompat;
import android.text.TextUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.RemoteMessage;
import org.openremote.android.service.AlertAction;
import org.openremote.android.service.AlertButton;
@@ -146,6 +147,12 @@ public class ORFirebaseMessagingService extends com.google.firebase.messaging.Fi
}
}
+ @Override
+ public void onNewToken(String s) {
+ super.onNewToken(s);
+ tokenService.sendOrStoreFCMToken(s, FirebaseInstanceId.getInstance().getId());
+ }
+
@RequiresApi(Build.VERSION_CODES.O)
private void createNotificationChannel() {
String channelName = "OR Eindhoven Message Service";
diff --git a/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java b/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
index 96e07d1cb..4e2a98068 100644
--- a/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
+++ b/console/android/src/main/java/org/openremote/android/ORMessagingActionService.java
@@ -6,7 +6,7 @@ import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
-import android.support.annotation.Nullable;
+import androidx.annotation.Nullable;
import android.text.TextUtils;
import org.openremote.android.service.TokenService;
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 f70b04a71..314110636 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
@@ -7,13 +7,10 @@ import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
-import android.support.v4.app.ActivityCompat
-import android.support.v4.content.ContextCompat
+import androidx.core.app.ActivityCompat
+import androidx.core.content.ContextCompat
import com.fasterxml.jackson.databind.ObjectMapper
-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 com.google.android.gms.location.*
import org.openremote.android.MainActivity
import org.openremote.android.R
import java.net.URL
@@ -24,7 +21,7 @@ import kotlin.concurrent.schedule
class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissionsResultCallback {
- interface EnableCallback {
+ interface GeofenceCallback {
fun accept(responseData: Map<String, Any>)
}
@@ -53,7 +50,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
fun getGeofences(context: Context): Array<GeofenceDefinition> {
val sharedPreferences = context.getSharedPreferences(context.getString(R.string.OR_CONSOLE_NAME), Context.MODE_PRIVATE)
val existingGeofencesJson = sharedPreferences.getString(geofencesKey, null)
- var geofences : Array<GeofenceDefinition> = arrayOf()
+ var geofences: Array<GeofenceDefinition> = arrayOf()
if (existingGeofencesJson != null) {
geofences = JSON.readValue(existingGeofencesJson, Array<GeofenceDefinition>::class.java)
}
@@ -136,7 +133,33 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
LocationServices.getGeofencingClient(context)
}
- var enableCallback: EnableCallback? = null
+ private val locationClient: FusedLocationProviderClient by lazy {
+ LocationServices.getFusedLocationProviderClient(context)
+ }
+
+ private val locationUpdateCallback: LocationCallback by lazy {
+ object : LocationCallback() {
+ override fun onLocationResult(locationResult: LocationResult?) {
+ locationResult?.lastLocation?.let {
+ locationClient.removeLocationUpdates(this)
+ locationCallback?.accept(hashMapOf(
+ "action" to "GET_LOCATION",
+ "provider" to "geofence",
+ "data" to hashMapOf(
+ "latitude" to it.latitude,
+ "longitude" to it.longitude
+ )
+ ))
+ locationCallback = null
+ }
+ }
+ }
+ }
+
+ private lateinit var locationRequest: LocationRequest
+
+ private var enableCallback: GeofenceCallback? = null
+ private var locationCallback: GeofenceCallback? = null
fun initialize(): Map<String, Any> {
val sharedPreferences = context.getSharedPreferences(context.getString(R.string.OR_CONSOLE_NAME), Context.MODE_PRIVATE)
@@ -154,7 +177,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
}
@SuppressLint("MissingPermission")
- fun enable(activity: Activity, baseUrl: String, consoleId: String, callback: EnableCallback) {
+ fun enable(activity: Activity, baseUrl: String, consoleId: String, callback: GeofenceCallback) {
val sharedPreferences = context.getSharedPreferences(context.getString(R.string.OR_CONSOLE_NAME), Context.MODE_PRIVATE)
sharedPreferences.edit()
@@ -163,7 +186,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
.remove(geofenceDisabledKey)
.apply()
- if(ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
+ if (ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
enableCallback = callback
registerPermissions(activity)
return
@@ -187,6 +210,29 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
//context.stopService(Intent(context, LocationService::class.java))
}
+ fun getLocation(activity: Activity, callback: GeofenceCallback?) {
+ locationCallback = callback
+
+
+ val hasPermission = ContextCompat.checkSelfPermission(context, ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
+
+ if (hasPermission) {
+ locationRequest = LocationRequest.create()
+ locationRequest.priority = LocationRequest.PRIORITY_HIGH_ACCURACY
+ locationRequest.numUpdates = 1
+
+ locationClient.requestLocationUpdates(locationRequest, locationUpdateCallback, null)
+ } else {
+ registerPermissions(activity)
+ locationCallback?.accept(hashMapOf(
+ "action" to "GET_LOCATION",
+ "provider" to "geofence",
+ "data" to hashMapOf<String, Any>()
+ ))
+ locationCallback = null
+ }
+ }
+
fun refreshGeofences() {
LOG.info("Refresh geofences")
@@ -228,7 +274,7 @@ class GeofenceProvider(val context: Context) : ActivityCompat.OnRequestPermissio
}
}
- private fun onEnable(callback: EnableCallback?) {
+ private fun onEnable(callback: GeofenceCallback?) {
LOG.info("Enabling geofence provider")