Panagiotis Triantafyllou

version 4.5.3

......@@ -32,13 +32,13 @@ public class SplashActivity extends BaseActivity {
@Override
public void onWarplyInitTimeOut() {
showToast("Warply initialization timeout!");
finish();
checkForAppUpdate();
}
@Override
public void onWarplyPermissionsDenied() {
showToast("Warply permissions denied!");
// onWarplyReady();
checkForAppUpdate();
}
});
}
......@@ -55,7 +55,7 @@ public class SplashActivity extends BaseActivity {
// super.onRequestPermissionsResult(requestCode, permissions, grantResults);
// }
private void checkForAppUpdate(){
private void checkForAppUpdate() {
Warply.checkForAppUpdate(SplashActivity.this, new SimpleCallbackReceiver<Boolean>() {
@Override
......
......@@ -2,7 +2,7 @@ apply plugin: 'com.android.library'
ext {
PUBLISH_GROUP_ID = 'ly.warp'
PUBLISH_VERSION = '4.5.2'
PUBLISH_VERSION = '4.5.3'
PUBLISH_ARTIFACT_ID = 'warply-android-sdk'
}
......@@ -48,6 +48,7 @@ dependencies {
//------------------------------ GMS -----------------------------//
api 'com.google.android.gms:play-services-base:18.0.1'
api 'com.google.android.gms:play-services-location:19.0.1'
//------------------------------ Work Manager -----------------------------//
api 'androidx.work:work-runtime:2.7.1'
......
......@@ -25,6 +25,8 @@
package ly.warp.sdk;
import static ly.warp.sdk.utils.constants.WarpConstants.IN_APP_FILTER_ALL;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
......@@ -33,11 +35,10 @@ import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import androidx.appcompat.app.AlertDialog;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
......@@ -47,47 +48,24 @@ import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import ly.warp.sdk.db.WarplyDBHelper;
import ly.warp.sdk.io.callbacks.BaseCallbackReceiver;
import ly.warp.sdk.io.callbacks.CallbackReceiver;
import ly.warp.sdk.io.callbacks.CampaignsHook;
import ly.warp.sdk.io.callbacks.ContactHook;
import ly.warp.sdk.io.callbacks.ContentHook;
import ly.warp.sdk.io.callbacks.InboxStatsHook;
import ly.warp.sdk.io.callbacks.PostHook;
import ly.warp.sdk.io.callbacks.ProductsHook;
import ly.warp.sdk.io.callbacks.MerchantCategoriesHook;
import ly.warp.sdk.io.callbacks.MerchantsHook;
import ly.warp.sdk.io.callbacks.SimpleCallbackReceiver;
import ly.warp.sdk.io.callbacks.TagsCategoriesHook;
import ly.warp.sdk.io.callbacks.TagsHook;
import ly.warp.sdk.io.callbacks.VolleyTransformer;
import ly.warp.sdk.io.callbacks.WarplyReadyCallback;
import ly.warp.sdk.io.models.Campaign;
import ly.warp.sdk.io.models.CampaignList;
import ly.warp.sdk.io.models.ContentList;
import ly.warp.sdk.io.models.InboxStats;
import ly.warp.sdk.io.models.ProductList;
import ly.warp.sdk.io.models.MerchantCategoriesList;
import ly.warp.sdk.io.models.MerchantList;
import ly.warp.sdk.io.models.TagsCategoriesList;
import ly.warp.sdk.io.models.TagsList;
import ly.warp.sdk.io.request.WarplyContactRequest;
import ly.warp.sdk.io.request.WarplyContentRequest;
import ly.warp.sdk.io.request.WarplyInboxRequest;
import ly.warp.sdk.io.request.WarplyJsonArrayRequest;
import ly.warp.sdk.io.request.WarplyJsonObjectRequest;
import ly.warp.sdk.io.request.WarplyProductsRequest;
import ly.warp.sdk.io.request.WarplyMerchantCategoriesRequest;
import ly.warp.sdk.io.request.WarplyMerchantsRequest;
import ly.warp.sdk.io.request.WarplyTagsCategoriesRequest;
import ly.warp.sdk.io.request.WarplyTagsRequest;
import ly.warp.sdk.io.volley.AuthFailureError;
import ly.warp.sdk.io.volley.Request.Method;
import ly.warp.sdk.io.volley.RequestQueue;
import ly.warp.sdk.io.volley.toolbox.Volley;
......@@ -95,8 +73,8 @@ import ly.warp.sdk.receivers.WarplyBeaconsApplication;
import ly.warp.sdk.utils.GCMRegistrar;
import ly.warp.sdk.utils.ObjectSerializer;
import ly.warp.sdk.utils.WarpUtils;
import ly.warp.sdk.utils.WarplyInitializer;
import ly.warp.sdk.utils.WarplyDeviceInfoCollector;
import ly.warp.sdk.utils.WarplyInitializer;
import ly.warp.sdk.utils.WarplyPreferences;
import ly.warp.sdk.utils.WarplyProperty;
import ly.warp.sdk.utils.constants.WarpConstants;
......@@ -108,8 +86,6 @@ import ly.warp.sdk.utils.managers.WarplyServerPreferencesManager;
import ly.warp.sdk.utils.managers.WarplyUserManager;
import ly.warp.sdk.views.dialogs.InAppDialog;
import static ly.warp.sdk.utils.constants.WarpConstants.IN_APP_FILTER_ALL;
public enum Warply {
INSTANCE;
......@@ -864,10 +840,8 @@ public enum Warply {
isInitializedOrThrow();
WarpUtils.log("************* WARPLY Microapp ********************");
if (!WarplyServerPreferencesManager
.isMicroAppActive(WarpConstants.MicroApp.APPLICATION_DATA)) {
WarpUtils
.log("[WARP Trace] Application Info Microapp is not active");
if (!WarplyServerPreferencesManager.isMicroAppActive(WarpConstants.MicroApp.APPLICATION_DATA)) {
WarpUtils.log("[WARP Trace] Application Info Microapp is not active");
return;
} else {
WarpUtils.log("[WARP Trace] Application Info Microapp is active");
......@@ -882,100 +856,12 @@ public enum Warply {
super.onResult(json, errorCode);
if (json != null) {
// String jString = json.toString();
// if (!jString.equalsIgnoreCase(WarpUtils.getLastDeviceInfo(mContext.get()))) {
if (!WarpUtils.getIsDeviceInfoSaved(mContext.get()) && !WarpUtils.getIsWarped(mContext.get())) {
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
if (!WarpUtils.getIsDeviceInfoSaved(mContext.get())) {
WarpUtils.setIsDeviceInfoSaved(mContext.get(), true);
WarpUtils.setIsWarped(mContext.get(), true);
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
} else if (!WarpUtils.getIsDeviceInfoSaved(mContext.get()) && WarpUtils.getIsWarped(mContext.get())) {
if (WarpUtils.getIsWarped(mContext.get()) && !WarpUtils.getDeviceToken(mContext.get()).equals(WarpUtils.getRegistrationGCM(mContext.get()))) {
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
WarpUtils.setIsDeviceInfoSaved(mContext.get(), true);
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
} else {
String gcm;
gcm = (String) json.remove("registration_gcm");
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setIsDeviceInfoSaved(mContext.get(), true);
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
}
} else if (WarpUtils.getIsDeviceInfoSaved(mContext.get()) && !WarpUtils.getIsWarped(mContext.get())) {
if (WarpUtils.getIsDeviceInfoSaved(mContext.get()) && hasDeviceInfoDifference(WarpUtils.getDeviceInfoObject(mContext.get()), json)) {
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setIsWarped(mContext.get(), true);
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
} else {
JSONObject deviceTokenJson = new JSONObject();
try {
deviceTokenJson.putOpt("registration_gcm", WarpUtils.getRegistrationGCM(mContext.get()));
} catch (JSONException e) {
WarpUtils.log("************* WARPLY Warning ********************");
WarpUtils.log("Problem when creating Registration GCM Token JSON", e);
WarpUtils.log("*************************************************");
}
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(deviceTokenJson.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
WarpUtils.setIsWarped(mContext.get(), true);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, deviceTokenJson, true);
}
} else if (WarpUtils.getIsDeviceInfoSaved(mContext.get()) && WarpUtils.getIsWarped(mContext.get())) {
if (WarpUtils.getDeviceToken(mContext.get()).equals(WarpUtils.getRegistrationGCM(mContext.get())) && hasDeviceInfoDifference(WarpUtils.getDeviceInfoObject(mContext.get()), json)) {
String gcm;
gcm = (String) json.remove("registration_gcm");
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
} else if (!WarpUtils.getDeviceToken(mContext.get()).equals(WarpUtils.getRegistrationGCM(mContext.get())) && !hasDeviceInfoDifference(WarpUtils.getDeviceInfoObject(mContext.get()), json)) {
JSONObject deviceTokenJson = new JSONObject();
try {
deviceTokenJson.putOpt("registration_gcm", WarpUtils.getRegistrationGCM(mContext.get()));
} catch (JSONException e) {
WarpUtils.log("************* WARPLY Warning ********************");
WarpUtils.log("Problem when creating Registration GCM Token JSON", e);
WarpUtils.log("*************************************************");
}
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(deviceTokenJson.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, deviceTokenJson, true);
} else if (!WarpUtils.getDeviceToken(mContext.get()).equals(WarpUtils.getRegistrationGCM(mContext.get())) && hasDeviceInfoDifference(WarpUtils.getDeviceInfoObject(mContext.get()), json)) {
WarpUtils.log("********** DeviceInfo **********");
WarpUtils.log(json.toString());
WarpUtils.log("********************************");
WarpUtils.setDeviceToken(mContext.get(), WarpUtils.getRegistrationGCM(mContext.get()));
} else {
if (hasDeviceInfoDifference(WarpUtils.getDeviceInfoObject(mContext.get()), json)) {
WarpUtils.setDeviceInfoObject(mContext.get(), json);
postMicroappData(WarpConstants.MICROAPP_DEVICE_INFO, json, true);
}
......@@ -1039,16 +925,15 @@ public enum Warply {
PackageInfo info = mContext.get().getPackageManager().getPackageInfo(mContext.get().getApplicationContext().getPackageName(), 0);
object.putOpt("app_version", info.versionName);
object.putOpt("app_build", info.versionCode);
String jString = object.toString();
// if ((jString.equals(WarpUtils.getLastApplicationData(mContext.get()))) == Boolean.FALSE) {
// WarpUtils.setLastApplicationData(mContext.get(), jString);
if (!WarpUtils.getHasApplicationInfo(mContext.get())) {
WarpUtils.setHasApplicationInfo(mContext.get(), true);
WarpUtils.setAppDataObject(mContext.get(), object);
postMicroappData(WarpConstants.MICROAPP_APPLICATION_DATA, object, force);
} else if (WarpUtils.getHasApplicationInfo(mContext.get()) && hasApplicationDataDifference(WarpUtils.getAppDataObject(mContext.get()), object)) {
WarpUtils.setAppDataObject(mContext.get(), object);
postMicroappData(WarpConstants.MICROAPP_APPLICATION_DATA, object, force);
} else {
if (hasApplicationDataDifference(WarpUtils.getAppDataObject(mContext.get()), object)) {
WarpUtils.setAppDataObject(mContext.get(), object);
postMicroappData(WarpConstants.MICROAPP_APPLICATION_DATA, object, force);
}
}
} catch (JSONException e) {
WarpUtils.warn("Problem when creating Device Info JSON", e);
......@@ -1139,10 +1024,10 @@ public enum Warply {
registerWarply();
return;
}
// if (WarpUtils.getIsAPPDATAENABLED(mContext.get()))
// postApplicationData(true);
// if (WarpUtils.getIsDEVICEINFOENABLED(mContext.get()))
// postDeviceInfoData();
if (WarpUtils.getIsAPPDATAENABLED(mContext.get()))
postApplicationData(true);
if (WarpUtils.getIsDEVICEINFOENABLED(mContext.get()))
postDeviceInfoData();
tryWakingSendingTaskInternal(WarplyDBHelper.getInstance(mContext.get())
.getRequestsInQueueCount());
}
......@@ -1767,4 +1652,4 @@ public enum Warply {
}
};
}
}
\ No newline at end of file
......
......@@ -39,7 +39,7 @@ import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import java.util.Random;
import java.security.SecureRandom;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
......@@ -75,6 +75,7 @@ public class WarpViewActivity extends WarpBaseActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
WarplySessionManager.onCreateActivity(this);
initViews();
Warply.getInitializer(this).init();
setPageAccordingToIntent();
......@@ -203,7 +204,7 @@ public class WarpViewActivity extends WarpBaseActivity {
if (Build.VERSION.SDK_INT >= 21) {
return ThreadLocalRandom.current().nextInt(RANDOM_MIN, RANDOM_MAX + 1);
} else {
Random rand = new Random();
SecureRandom rand = new SecureRandom();
return rand.nextInt((RANDOM_MAX - RANDOM_MIN) + 1) + RANDOM_MIN;
}
}
......
......@@ -84,11 +84,11 @@ public class VolleyTransformer implements Listener<JSONObject>, ErrorListener {
if (response.optJSONObject("context") != null) {
if (response.optJSONObject("context").optJSONObject("device_status") != null) {
WarpUtils.setIsWarped(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("warped"));
WarpUtils.setDeviceToken(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optString("device_token"));
WarpUtils.setHasApplicationInfo(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("application_info_saved"));
// WarpUtils.setDeviceToken(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optString("device_token"));
// WarpUtils.setHasApplicationInfo(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("application_info_saved"));
WarpUtils.setDeviceId(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optString("device_id"));
WarpUtils.setIsDeviceIdSaved(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("device_id_saved"));
WarpUtils.setIsDeviceInfoSaved(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("device_info_saved"));
// WarpUtils.setIsDeviceInfoSaved(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optBoolean("device_info_saved"));
if (response.optJSONObject("context").optJSONObject("device_status").optJSONObject("application_info") != null) {
WarpUtils.setAppDataObject(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optJSONObject("application_info"));
WarpUtils.setSDKVersion(getWarplyContext(), response.optJSONObject("context").optJSONObject("device_status").optJSONObject("application_info").optString("sdk_version"));
......
/*
* Copyright 2010-2013 Warply Ltd. All rights reserved.
*
*
* Redistribution and use in source and binary forms, without modification, are
* permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
*
* THIS SOFTWARE IS PROVIDED BY THE WARPLY LTD ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
......@@ -34,7 +34,9 @@ import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Build;
import java.util.HashMap;
import java.util.Map;
public class LocationChangedReceiver extends BroadcastReceiver {
......@@ -44,9 +46,6 @@ public class LocationChangedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Log.i("Location receiver", Integer.toString(counter++));
isAppShutDown = WarplyLocationManager.waprplyContext == null;
/**
......@@ -64,23 +63,14 @@ public class LocationChangedReceiver extends BroadcastReceiver {
}
if (intent.hasExtra(LocationManager.KEY_LOCATION_CHANGED)) {
new WarplyPreferences(context).saveUpdateLocationServiceStatus("on");
Location location = (Location) intent.getExtras().get(LocationManager.KEY_LOCATION_CHANGED);
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// context.startForegroundService(new Intent(context, UpdateUserLocationService.class)
// .putExtra("LOCATION_KEY", location));
// } else {
// context.startService(new Intent(context, UpdateUserLocationService.class)
// .putExtra("LOCATION_KEY", location));
// }
UpdateUserLocationService.enqueueWork(context, new Intent(context, UpdateUserLocationService.class)
.putExtra("LOCATION_KEY", location));
Map<String, Object> mLocValues = new HashMap<>();
mLocValues.put("latitude", location.getLatitude());
mLocValues.put("longitude", location.getLongitude());
UpdateUserLocationService.scheduleWork(context, mLocValues);
}
}
}
}
\ No newline at end of file
......
......@@ -28,8 +28,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
......@@ -98,6 +98,7 @@ public class FCMBaseMessagingService extends FirebaseMessagingService {
public void onNewToken(@NonNull String s) {
super.onNewToken(s);
GCMRegistrar.setRegistrationId(this, s);
WarpUtils.setDeviceToken(this, s);
}
@Override
......@@ -146,7 +147,7 @@ public class FCMBaseMessagingService extends FirebaseMessagingService {
if (Build.VERSION.SDK_INT >= 21) {
return ThreadLocalRandom.current().nextInt(RANDOM_MIN, RANDOM_MAX + 1);
} else {
Random rand = new Random();
SecureRandom rand = new SecureRandom();
return rand.nextInt((RANDOM_MAX - RANDOM_MIN) + 1) + RANDOM_MIN;
}
}
......@@ -164,7 +165,7 @@ public class FCMBaseMessagingService extends FirebaseMessagingService {
WarpUtils.log("Showing campaign with session UUID: " + pc.getSessionUUID());
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (!TextUtils.isEmpty(pc.getSessionUUID())) {
......@@ -297,7 +298,7 @@ public class FCMBaseMessagingService extends FirebaseMessagingService {
public void showNotification(Context context, String title, String ticker,
String message, Intent newIntent, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
WarpUtils.log("Showing notification with tag: " + tag + " and id: "
+ id);
......@@ -343,7 +344,7 @@ public class FCMBaseMessagingService extends FirebaseMessagingService {
public void showNotification(Context context, PushCampaign pc, Intent newIntent, List<NotificationCompat.Action> actions, RemoteViews remoteViews, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (id > 0) {
uid = id;
......
......@@ -39,7 +39,7 @@ import android.os.SystemClock;
import androidx.core.app.NotificationCompat;
import android.util.Log;
import java.util.Random;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
import ly.warp.sdk.utils.GCMRegistrar;
......@@ -74,7 +74,7 @@ public abstract class GCMBaseIntentService extends IntentService {
// instance counter
private static int sCounter = 0;
private static final Random sRandom = new Random();
private static final SecureRandom sRandom = new SecureRandom();
private static final int MAX_BACKOFF_MS = (int) TimeUnit.SECONDS
.toMillis(3600); // 1 hour
......
......@@ -14,7 +14,6 @@ import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.RemoteViews;
import androidx.core.app.NotificationCompat;
......@@ -33,9 +32,9 @@ import org.json.JSONObject;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.TimeUnit;
......@@ -91,18 +90,15 @@ public class HMSBaseMessagingService extends HmsMessageService {
// ===========================================================
// URLThread class
// ===========================================================
public static class URLThread extends Thread
{
public static class URLThread extends Thread {
private String urlString = "";
public URLThread(String url)
{
public URLThread(String url) {
this.urlString = url;
}
@Override
public void run()
{
public void run() {
try {
URL url;
HttpURLConnection urlConnection = null;
......@@ -138,7 +134,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
public void onNewToken(String s, Bundle bundle) {
super.onNewToken(s, bundle);
GCMRegistrar.setRegistrationId(this, s);
Log.v("HUAWEI TOKEN", "receive token:" + s);
WarpUtils.setDeviceToken(this, s);
}
@Override
......@@ -146,7 +142,6 @@ public class HMSBaseMessagingService extends HmsMessageService {
super.onMessageReceived(remoteMessage);
JSONObject data = new JSONObject(remoteMessage.getDataOfMap());
Log.v("DATA", "data is " + data);
if (data == null || !data.has("loyalty-action")) {
return;
}
......@@ -197,7 +192,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
if (Build.VERSION.SDK_INT >= 21) {
return ThreadLocalRandom.current().nextInt(RANDOM_MIN, RANDOM_MAX + 1);
} else {
Random rand = new Random();
SecureRandom rand = new SecureRandom();
return rand.nextInt((RANDOM_MAX - RANDOM_MIN) + 1) + RANDOM_MIN;
}
}
......@@ -215,7 +210,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
WarpUtils.log("Showing campaign with session UUID: " + pc.getSessionUUID());
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (!TextUtils.isEmpty(pc.getSessionUUID())) {
......@@ -346,7 +341,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
public void showNotification(Context context, String title, String ticker,
String message, Intent newIntent, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
WarpUtils.log("Showing notification with tag: " + tag + " and id: "
+ id);
......@@ -392,7 +387,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
public void showNotification(Context context, PushCampaign pc, Intent newIntent, List<NotificationCompat.Action> actions, RemoteViews remoteViews, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (id > 0) {
uid = id;
......@@ -544,7 +539,7 @@ public class HMSBaseMessagingService extends HmsMessageService {
private static Bitmap loadDrawable(final String urlString) {
if (urlString == null || TextUtils.isEmpty(urlString))
return null;
return null;
// alternative solution to thread but only in debug mode
// StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
......@@ -569,10 +564,10 @@ public class HMSBaseMessagingService extends HmsMessageService {
public static Bundle jsonToBundle(JSONObject jsonObject) throws JSONException {
Bundle bundle = new Bundle();
Iterator iter = jsonObject.keys();
while(iter.hasNext()){
String key = (String)iter.next();
while (iter.hasNext()) {
String key = (String) iter.next();
String value = jsonObject.getString(key);
bundle.putString(key,value);
bundle.putString(key, value);
}
return bundle;
}
......
......@@ -25,18 +25,23 @@
package ly.warp.sdk.services;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.core.app.JobIntentService;
import androidx.work.Data;
import androidx.work.ExistingPeriodicWorkPolicy;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.CancellationToken;
import com.google.android.gms.tasks.OnTokenCanceledListener;
import org.json.JSONArray;
import org.json.JSONException;
......@@ -44,120 +49,77 @@ import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import ly.warp.sdk.BuildConfig;
import ly.warp.sdk.Warply;
import ly.warp.sdk.dexter.listener.DexterError;
import ly.warp.sdk.dexter.listener.PermissionDeniedResponse;
import ly.warp.sdk.io.callbacks.CallbackReceiver;
import ly.warp.sdk.io.models.WarpGeoFence;
import ly.warp.sdk.receivers.LocationChangedReceiver;
import ly.warp.sdk.utils.PermissionsUtil;
import ly.warp.sdk.utils.WarpJSONParser;
import ly.warp.sdk.utils.WarpUtils;
import ly.warp.sdk.utils.WarplyPreferences;
import ly.warp.sdk.utils.constants.WarpConstants;
import ly.warp.sdk.utils.managers.WarplyLocationManager;
import static ly.warp.sdk.utils.constants.WarpConstants.JOB_SERVICE_ID;
public class UpdateUserLocationService extends Worker {
public class UpdateUserLocationService extends /*Service*/ JobIntentService {
public static final String TAG = "LOCATION_KEY";
Timer timer;
int lastForProvider;
float lastForTime;
double lastForDistance;
int lastBacProvider;
float lastBacTime;
double lastBacDistance;
boolean geofencingEnabled = false;
private int lastForProvider;
private float lastForTime;
private double lastForDistance;
private int lastBacProvider;
private float lastBacTime;
private double lastBacDistance;
private boolean geofencingEnabled = false;
//Geofences
private List<WarpGeoFence> geofences = null;
int defaultCheckInterval = 30;
private static int defaultCheckInterval = 15;
private final static int defaultInterval = 15;
@Override
public void onCreate() {
timer = new Timer();
timer.schedule(new firstTask(), 0, defaultCheckInterval * 1000);
super.onCreate();
public UpdateUserLocationService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
super(context, workerParams);
}
// @Override
// public int onStartCommand(Intent intent, int flags, int startId) {
//
// if (intent != null) {
// Location location = intent.getParcelableExtra("LOCATION_KEY");
// if (location != null) {
// //fences
// if(isGeofencingEnabled()) {
// if (isInsideFence(location.getLatitude(), location.getLongitude())) {
// sendLocationData(location.getLatitude(), location.getLongitude());
// }
// }
// else{
// sendLocationData(location.getLatitude(), location.getLongitude());
// }
// }
// }
// // If we get killed, after returning from here, do not restart if there
// // is no other intent pending
// return START_NOT_STICKY;
// }
@NonNull
@Override
protected void onHandleWork(@NonNull Intent intent) {
Location location = intent.getParcelableExtra("LOCATION_KEY");
if (location != null) {
//fences
if (isGeofencingEnabled()) {
if (isInsideFence(location.getLatitude(), location.getLongitude())) {
sendLocationData(location.getLatitude(), location.getLongitude());
public Result doWork() {
if (Warply.getWarplyContext() != null) {
if (new WarplyPreferences(Warply.getWarplyContext()).getAppStatus().equals("foreground")
/*&& new WarplyPreferences(Warply.getWarplyContext()).getUpdateLocationServiceStatus().equals("on")*/) {
try {
new PermissionsUtil(
Warply.getWarplyContext(),
mPermissionsCallback,
PermissionsUtil.PERMISSION_LOCATION_COARSE,
PermissionsUtil.PERMISSION_LOCATION_FINE
).requestPermissions();
} catch (SecurityException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
WorkManager.getInstance(Warply.getWarplyContext()).cancelAllWorkByTag(TAG);
}
}
} else {
sendLocationData(location.getLatitude(), location.getLongitude());
WorkManager.getInstance(Warply.getWarplyContext()).cancelAllWorkByTag(TAG);
}
} else {
WorkManager.getInstance(getApplicationContext()).cancelAllWorkByTag(TAG);
}
}
// @Override
// public IBinder onBind(Intent arg0) {
// // We don't provide binding, so return null
// return null;
// }
regulateLocationReporting();
// tells handler to send a message
class firstTask extends TimerTask {
@Override
public void run() {
handler.sendEmptyMessage(0);
}
return Result.success();
}
final Handler handler = new Handler(new Callback() {
@Override
public boolean handleMessage(Message msg) {
if (Warply.getWarplyContext() != null) {
if ((new WarplyPreferences(Warply.getWarplyContext()).getUpdateLocationServiceStatus()).equals("off")) {
timer.cancel();
stopSelf();
} else {
if (isGeofencingEnabled() && (getGeofences() == null || getGeofences().isEmpty()))
retrieveGeofences();
}
}
Log.i("regulation", "regulation started");
regulateLocationReporting();
return false;
}
});
private void sendLocationData(double lat, double lon) {
JSONObject jObj = new JSONObject();
try {
jObj.putOpt("action", WarpConstants.MICROAPP_GEOFENCING_ACTION);
......@@ -169,31 +131,41 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
}
if (LocationChangedReceiver.wClient != null) {
Warply.postReceiveMicroappData(WarpConstants.MICROAPP_GEOFENCING, jObj, new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
WarpUtils.log("success sending location " + result.toString());
}
@Override
public void onFailure(int errorCode) {
WarpUtils.log("failed during sending location data with error " + errorCode);
}
});
} else {
WarpUtils.log("Could not send user location data. You must registrer to warply first");
}
}
private void sendLocation(Location location) {
if (isGeofencingEnabled()) {
if (isInsideFence(location.getLatitude(), location.getLongitude())) {
sendLocationData(location.getLatitude(), location.getLongitude());
}
} else {
sendLocationData(location.getLatitude(), location.getLongitude());
}
if (isGeofencingEnabled() && (getGeofences() == null || getGeofences().isEmpty()))
retrieveGeofences();
}
// ------------------- Geofencing -------------------
// ------------------- Geofencing -------------------
private void retrieveGeofences() {
if (!isGeofencingEnabled())
return;
JSONObject jObj = new JSONObject();
try {
jObj.putOpt("action", WarpConstants.MICROAPP_GEOFENCING_ACTION_GET_POIS);
......@@ -201,6 +173,7 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
WarpUtils.log("JSON Exception thrown while creating the object in retrieveGeofences at WarplyLocationManager", e);
return;
}
if (LocationChangedReceiver.wClient != null) {
Warply.postReceiveMicroappData(WarpConstants.MICROAPP_GEOFENCING, jObj, new CallbackReceiver<JSONObject>() {
@Override
......@@ -244,18 +217,14 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
}
// ------------------- Location Modes -------------------
// ------------------- Location Modes -------------------
private void regulateLocationReporting() {
Warply.getContext(new CallbackReceiver<JSONObject>() {
@Override
public void onSuccess(JSONObject result) {
JSONObject json = result.optJSONObject("context");
if (json != null) {
JSONObject appDataJson = json.optJSONObject("application_data");
if (appDataJson != null) {
// location settings
......@@ -277,16 +246,7 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
Log.i("notification interval", Integer.toString(interval));
if (interval != defaultCheckInterval) {
defaultCheckInterval = interval;
timer.cancel();
timer = new Timer();
timer.schedule(new firstTask(), 0,
defaultCheckInterval * 1000); // 86400 sec
// reschedule every
// day
}
Context context = Warply.getWarplyContext();
......@@ -299,7 +259,6 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
WarplyLocationManager.disableConnectivityChangedReceiver(context);
} else if (foregroundProvider == WarpConstants.LocationModes.OFF.ordinal()) {
/*
* in case foreground provider is off and app is in
* foreground mode then app should stop reporting the
......@@ -307,7 +266,6 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
*/
if (!LocationChangedReceiver.isAppShutDown && appStatus.equals("foreground")) {
WarplyLocationManager.stopReportingLocation(context);
/*
* in case background provider is on and app is in
* background mode or shut down then app should check for
......@@ -333,7 +291,6 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
} else if (backgroundProvider == WarpConstants.LocationModes.OFF.ordinal()) {
/*
* in case background provider is off and app is in
* background mode then app should stop reporting the
......@@ -341,7 +298,6 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
*/
if (LocationChangedReceiver.isAppShutDown || appStatus.equals("background")) {
WarplyLocationManager.stopReportingLocation(context);
/*
* in case foreground provider is on and app is in
* foreground mode then app should check for settings
......@@ -365,9 +321,7 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
}
} else { // cases foreground and background providers are on
if (!LocationChangedReceiver.isAppShutDown && appStatus.equals("foreground")) {
if (!((lastForProvider == foregroundProvider)
&& (lastForTime == foregroundMinTime)
&& (lastForDistance == foregroundMinDistance))) {
......@@ -383,10 +337,8 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
lastForDistance = foregroundMinDistance;
}
} else if (!((lastBacProvider == backgroundProvider)
&& (lastBacTime == backgroundMinTime) && (lastBacDistance == backgroundMinDistance))) {
if (WarplyLocationManager.getLocationManager() == null)
WarplyLocationManager.instantiateLocationManager();
......@@ -401,18 +353,15 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
lastBacDistance = backgroundMinDistance;
}
} // end else foregroundProvider = on and backgroundProvider =
// on
}
}
}
@Override
public void onFailure(int errorCode) {
WarpUtils.log("Error with code " + errorCode + " while checking location modes");
}
});
}
......@@ -425,7 +374,63 @@ public class UpdateUserLocationService extends /*Service*/ JobIntentService {
return geofencingEnabled;
}
public static void enqueueWork(Context context, Intent work) {
enqueueWork(context, UpdateUserLocationService.class, JOB_SERVICE_ID, work);
private static PeriodicWorkRequest buildWorkRequest(Map<String, Object> location) {
Data inputData = new Data.Builder().putAll(location).build();
return new PeriodicWorkRequest.Builder(UpdateUserLocationService.class, defaultInterval, TimeUnit.MINUTES)
.addTag(TAG)
.setInputData(inputData)
.build();
}
public static void scheduleWork(Context context, Map<String, Object> location) {
WorkManager.getInstance(context).enqueueUniquePeriodicWork(
TAG,
ExistingPeriodicWorkPolicy.KEEP,
buildWorkRequest(location));
}
private final PermissionsUtil.PermissionCallback mPermissionsCallback = new PermissionsUtil.PermissionCallback() {
@Override
public void onError(DexterError error) {
onPermissionDenied(null);
}
@Override
public void onPermissionDenied(List<PermissionDeniedResponse> denied) {
if (denied != null && denied.size() < 2)//1 location permission accepted
onPermissionsGranted();
}
@Override
public void onPermissionsGranted() {
try {
FusedLocationProviderClient locationClient = LocationServices.getFusedLocationProviderClient(Warply.getWarplyContext());
locationClient.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, new CancellationToken() {
@NonNull
@Override
public CancellationToken onCanceledRequested(@NonNull OnTokenCanceledListener onTokenCanceledListener) {
return null;
}
@Override
public boolean isCancellationRequested() {
return false;
}
})
.addOnSuccessListener(location1 -> {
if (location1 != null) {
sendLocation(location1);
}
})
.addOnFailureListener(e -> {
WarpUtils.log("Could not get location data.");
});
} catch (SecurityException e) {
if (BuildConfig.DEBUG) {
e.printStackTrace();
}
}
}
};
}
......
......@@ -52,8 +52,8 @@ import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.List;
import java.util.Random;
import ly.warp.sdk.Warply;
import ly.warp.sdk.activities.WarpViewActivity;
......@@ -145,7 +145,7 @@ public abstract class WarpBaseIntentService extends GCMBaseIntentService {
WarpUtils.log("Showing campaign with session UUID: " + pc.getSessionUUID());
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (!TextUtils.isEmpty(pc.getSessionUUID())) {
......@@ -277,7 +277,7 @@ public abstract class WarpBaseIntentService extends GCMBaseIntentService {
public void showNotification(Context context, String title, String ticker,
String message, Intent newIntent, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
WarpUtils.log("Showing notification with tag: " + tag + " and id: "
+ id);
......@@ -323,7 +323,7 @@ public abstract class WarpBaseIntentService extends GCMBaseIntentService {
public void showNotification(Context context, PushCampaign pc, Intent newIntent, List<NotificationCompat.Action> actions, RemoteViews remoteViews, String tag, int id) {
Random randomGenerator = new Random();
SecureRandom randomGenerator = new SecureRandom();
int uid = randomGenerator.nextInt(1000);
if (id > 0) {
uid = id;
......
......@@ -32,6 +32,7 @@ import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.core.app.NotificationCompat;
......@@ -91,7 +92,12 @@ public class WarpInAppNotificationService extends WarpBaseIntentService {
.putExtra(KEY_SUBTITLE, mNotificationSubtitle);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getBroadcast(this, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
} else {
pendingIntent = PendingIntent.getBroadcast(this, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
builder.setContentIntent(pendingIntent);
// builder.setFullScreenIntent(pendingIntent, true); // Heads up notification, always visible OR setPriority to HIGH and setContentIntent
NotificationManager nm = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
......@@ -106,14 +112,24 @@ public class WarpInAppNotificationService extends WarpBaseIntentService {
.putExtra(KEY_TITLE, title)
.putExtra(KEY_SUBTITLE, subtitle)
.putExtra(KEY_HEADS_UP, isHeadsUpNotification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
} else {
pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
}
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
}
public static void cancelInAppNotificationAlarm(Context context, @NonNull int uid) {
Intent notifyIntent = new Intent(context, WarplyInAppNotificationReceiver.class).putExtra(KEY_UID, uid);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
PendingIntent pendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT | PendingIntent.FLAG_MUTABLE);
} else {
pendingIntent = PendingIntent.getBroadcast(context, uid, notifyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
}
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
......
......@@ -2,10 +2,18 @@ package ly.warp.sdk.utils;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import ly.warp.sdk.dexter.listener.DexterError;
......@@ -13,25 +21,15 @@ import ly.warp.sdk.dexter.listener.PermissionDeniedResponse;
import ly.warp.sdk.io.callbacks.WarplyReadyCallback;
import ly.warp.sdk.utils.constants.WarpConstants;
public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequestPermissionsResultCallback */{
public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequestPermissionsResultCallback*/ {
// ===========================================================
// Constants
// ===========================================================
// private final String PREF_KEY_DENIED_PERMISSION_COUNT = "pref_key_denied_permissions_count";
private final long INIT_TIME_OUT = 1000 * 20;
private final long INIT_ATTEMPTS = 3;
// permissions
// private static final String[] DANGEROUS_PERMISSIONS = {
// android.Manifest.permission.ACCESS_FINE_LOCATION,
// android.Manifest.permission.ACCESS_COARSE_LOCATION,
// Manifest.permission.READ_PHONE_STATE,
// Manifest.permission.WRITE_EXTERNAL_STORAGE
// };
//
// private final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;
private final int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 3001;
private boolean mPermissionsResultRequested = false;
// ===========================================================
......@@ -39,10 +37,9 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
// ===========================================================
private Context mContext;
// private Activity mPermissionsActivity;
private Activity mPermissionsActivity;
private WarplyInitCallback mInitCallback;
private WarplyReadyCallback mReadyCallback;
// private WarplyPreferences mPreferences;
private static volatile Handler mMainThreadHandler;
private static volatile AtomicBoolean stopThreadLock;
......@@ -57,7 +54,6 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
this.mContext = context;
this.mReadyCallback = readyCallback;
this.mInitCallback = initCallback;
// this.mPreferences = new WarplyPreferences(mContext);
if (mMainThreadHandler == null) {
mMainThreadHandler = new Handler(Looper.getMainLooper());
......@@ -105,15 +101,14 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
// @Override
// public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//
// switch (requestCode) {
// case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS:
//
// if (permissions.length > 0) {
// Map<String, Integer> results = new HashMap<>();
// for (String permission : DANGEROUS_PERMISSIONS) {
// for (String permission : PermissionsUtil.DANGEROUS_PERMISSIONS) {
// results.put(permission, PackageManager.PERMISSION_GRANTED);
// }
//
// for (int i = 0; i < permissions.length; i++) {
// results.put(permissions[i], grantResults[i]);
// }
......@@ -128,10 +123,8 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
//
// if (mReadyCallback != null && mPermissionsActivity != null) {
// if (stillNeedRequest) {
// //mPermissionsActivity.finish();
// mReadyCallback.onWarplyPermissionsDenied();
// }
// // else {onResume() after close dialog of permission -> initWithPermissions()}
// }
// mPermissionsResultRequested = true;
// }
......@@ -179,6 +172,23 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
}
public synchronized void initWithPermissions(Activity activity) {
// this.mPermissionsActivity = activity;
//
// int result;
// List<String> listPermissionsNeeded = new ArrayList<>();
// for (String p : PermissionsUtil.DANGEROUS_PERMISSIONS) {
// result = ContextCompat.checkSelfPermission(activity, p);
// if (result != PackageManager.PERMISSION_GRANTED) {
// listPermissionsNeeded.add(p);
// }
// }
//
// if (!listPermissionsNeeded.isEmpty()) {
// ActivityCompat.requestPermissions(activity, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
//// init();
// }
// init();
PermissionsUtil permUtil = new PermissionsUtil(
activity,
new PermissionsUtil.PermissionCallback() {
......@@ -188,6 +198,7 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
if (mReadyCallback != null)
mReadyCallback.onWarplyPermissionsDenied();
}
@Override
public void onPermissionsGranted() {
mPermissionsResultRequested = true;
......@@ -195,47 +206,19 @@ public class WarplyInitializer extends Thread /*implements ActivityCompat.OnRequ
@Override
public void onError(DexterError error) {
if (error.toString().equals("REQUEST_ONGOING"))
return;
onPermissionDenied(null);
}
},
null //Requests all dangerous permissions
);
if(permUtil.requestNeeded() && !mPermissionsResultRequested){
if (permUtil.requestNeeded() && !mPermissionsResultRequested) {
permUtil.requestPermissions();
}
else{
} else {
mPermissionsResultRequested = true;
init();
}
// this.mPermissionsActivity = activity;
// final List<String> deniedPermissionsList = new ArrayList<>();
// for (String permission : DANGEROUS_PERMISSIONS) {
// if (ContextCompat.checkSelfPermission(mPermissionsActivity, permission)
// != PackageManager.PERMISSION_GRANTED) {
// deniedPermissionsList.add(permission);
// }
// }
// if (deniedPermissionsList.size() == 0 || mPermissionsResultRequested) {
//
// // reset warply initialization if was initialized
// // with wrong parameters without permissions or with another permissions count
// int oldDeniedPermissionsCount = mPreferences.getInt(PREF_KEY_DENIED_PERMISSION_COUNT, deniedPermissionsList.size());
// if (deniedPermissionsList.size() != oldDeniedPermissionsCount) {
// WarpUtils.invalidateRegistrationWarply(mContext);
// }
// mPreferences.saveInt(PREF_KEY_DENIED_PERMISSION_COUNT, deniedPermissionsList.size());
// init();
// } else {
// mPermissionsResultRequested = false;
// //TODO: restore permission request
//// ActivityCompat.requestPermissions(mPermissionsActivity,
//// deniedPermissionsList.toArray(new String[deniedPermissionsList.size()]),
//// REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
// mPreferences.saveInt(PREF_KEY_DENIED_PERMISSION_COUNT, deniedPermissionsList.size());
// init();
// }
}
// ===========================================================
......
......@@ -30,7 +30,7 @@ public class WarpConstants {
/**
* The version of the SDK installed in the device
*/
public static final String SDK_VERSION = "4.5.2";
public static final String SDK_VERSION = "4.5.3";
/**
* The URL of the server where it should ping
......
......@@ -32,6 +32,9 @@ import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Criteria;
import android.location.LocationManager;
import android.os.Build;
import androidx.work.WorkManager;
import java.util.List;
......@@ -97,11 +100,13 @@ public class WarplyLocationManager {
public void onError(DexterError error) {
onPermissionDenied(null);
}
@Override
public void onPermissionDenied(List<PermissionDeniedResponse> denied) {
if(denied != null && denied.size() < 2)//1 location permission accepted
if (denied != null && denied.size() < 2)//1 location permission accepted
onPermissionsGranted();
}
@Override
public void onPermissionsGranted() {
/*
......@@ -124,14 +129,14 @@ public class WarplyLocationManager {
}
};
try{
try {
new PermissionsUtil(
act,
callback,
PermissionsUtil.PERMISSION_LOCATION_COARSE,
PermissionsUtil.PERMISSION_LOCATION_FINE
).requestPermissions();
}catch (Exception e){
} catch (Exception e) {
if (BuildConfig.DEBUG)
e.printStackTrace();
}
......@@ -182,9 +187,15 @@ public class WarplyLocationManager {
public static void stopReportingLocation(Context wContext) {
if (locationManager != null) {
locationManager.removeUpdates(PendingIntent.getBroadcast(Warply.getWarplyContext(), 0,
new Intent(Warply.getWarplyContext(), LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
locationManager.removeUpdates(PendingIntent.getBroadcast(Warply.getWarplyContext(), 0,
new Intent(Warply.getWarplyContext(), LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE));
} else {
locationManager.removeUpdates(PendingIntent.getBroadcast(Warply.getWarplyContext(), 0,
new Intent(Warply.getWarplyContext(), LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT));
}
}
disableLocationChangedReceiver(wContext);
......@@ -197,10 +208,17 @@ public class WarplyLocationManager {
enableLocationChangedReceiver();
if (wContext != null) {
final PendingIntent locationListenerPendingIntent;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
locationListenerPendingIntent = PendingIntent.getBroadcast(wContext, 0,
new Intent(wContext, LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_MUTABLE);
} else {
locationListenerPendingIntent = PendingIntent.getBroadcast(wContext, 0,
new Intent(wContext, LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT);
}
final PendingIntent locationListenerPendingIntent = PendingIntent.getBroadcast(wContext, 0,
new Intent(wContext, LocationChangedReceiver.class),
PendingIntent.FLAG_UPDATE_CURRENT);
final LocationManager lm = (LocationManager) wContext.getSystemService(Context.LOCATION_SERVICE);
if (lm != null) {
......@@ -212,11 +230,13 @@ public class WarplyLocationManager {
public void onError(DexterError error) {
onPermissionDenied(null);
}
@Override
public void onPermissionDenied(List<PermissionDeniedResponse> denied) {
if(denied != null && denied.size() < 2)//1 location permission accepted
if (denied != null && denied.size() < 2)//1 location permission accepted
onPermissionsGranted();
}
@Override
public void onPermissionsGranted() {
try {
......@@ -323,6 +343,7 @@ public class WarplyLocationManager {
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
new WarplyPreferences(wContext).saveLocationChangedReceiverStatus("off");
WorkManager.getInstance(Warply.getWarplyContext()).cancelAllWorkByTag(UpdateUserLocationService.TAG);
}
private static void enableConnectivityChangedReceiver() {
......
......@@ -54,7 +54,7 @@ public class WarplySessionManager {
*/
public static void onCreateActivity(Activity activity) {
synchronized (_activities) {
Warply.getInitializer(activity).init();
// Warply.getInitializer(activity).init();
_activities.add(activity);
if (_activities.size() == 1)
onApplicationStart();
......@@ -74,7 +74,7 @@ public class WarplySessionManager {
*/
public static void onStartActivity(Activity activity) {
synchronized (_activities) {
Warply.getInitializer(activity).init();
// Warply.getInitializer(activity).init();
_activities.add(activity);
if (_activities.size() == 1)
onApplicationEnterForeground();
......@@ -106,14 +106,14 @@ public class WarplySessionManager {
private static void onApplicationEnterForeground() {
Warply.onApplicationEnterForeground();
_receiver = new ConnectivityReceiver();
_receiver.startTracking();
// _receiver = new ConnectivityReceiver();
// _receiver.startTracking();
}
private static void onApplicationEnterBackground() {
Warply.onApplicationEnterBackground();
if (_receiver != null)
_receiver.stopTracking();
// if (_receiver != null)
// _receiver.stopTracking();
}
private static class ConnectivityReceiver extends BroadcastReceiver {
......