From 110c5be9483ab488adaabba58001705af2868aaf Mon Sep 17 00:00:00 2001 From: charitha Date: Tue, 25 Apr 2017 10:40:05 +0530 Subject: [PATCH] Fixed intermittent login screen prompting & Improved location listening --- client/client/build.gradle | 4 +- client/client/src/main/AndroidManifest.xml | 2 +- .../iot/agent/AlreadyRegisteredActivity.java | 75 ++++++++++------- .../iot/agent/AuthenticationActivity.java | 73 ++++++++++------ .../wso2/iot/agent/RegistrationActivity.java | 84 ++++++++++--------- .../services/AgentDeviceAdminReceiver.java | 28 +++---- .../services/location/LocationService.java | 42 +++++----- client/iDPProxy/src/main/AndroidManifest.xml | 2 - .../iot/agent/proxy/AccessTokenHandler.java | 10 +-- .../wso2/iot/agent/proxy/IdentityProxy.java | 4 +- .../iot/agent/proxy/RefreshTokenHandler.java | 8 +- 11 files changed, 185 insertions(+), 147 deletions(-) diff --git a/client/client/build.gradle b/client/client/build.gradle index 44efd2b4..40290595 100644 --- a/client/client/build.gradle +++ b/client/client/build.gradle @@ -33,8 +33,8 @@ android { targetSdkVersion 23 multiDexEnabled true - versionCode 329 - versionName "3.1.15" + versionCode 330 + versionName "3.1.16" } buildTypes { release { diff --git a/client/client/src/main/AndroidManifest.xml b/client/client/src/main/AndroidManifest.xml index d05fea7d..cc0d8825 100644 --- a/client/client/src/main/AndroidManifest.xml +++ b/client/client/src/main/AndroidManifest.xml @@ -59,7 +59,7 @@ = 19) { + try { + int locationSetting = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); + if (locationSetting == 0) { + Intent enableLocationIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); + startActivity(enableLocationIntent); + Toast.makeText(context, R.string.msg_need_location, Toast.LENGTH_LONG).show(); + } + } catch (Settings.SettingNotFoundException e) { + Log.w(TAG, "Location setting is not available on this device"); } - } catch (Settings.SettingNotFoundException e) { - Log.w(TAG, "Location setting is not available on this device"); } } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + protected void onDestroy(){ + super.onDestroy(); + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.dismiss(); + progressDialog = null; + } + } + + @Override + public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { if (requestCode == 110) { + List missingPermissions = new ArrayList<>(); + for (int i =0; i < permissions.length; i++) { + if (grantResults[i] == PackageManager.PERMISSION_DENIED) { + missingPermissions.add(permissions[i]); + } + } + if (!missingPermissions.isEmpty()) { + Log.w(TAG, "Permissions not granted: " + missingPermissions.toString()); + } NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - mNotificationManager.cancel(Constants.TOKEN_EXPIRED, Constants.SIGN_IN_NOTIFICATION_ID); + mNotificationManager.cancel(Constants.PERMISSION_MISSING, Constants.PERMISSION_MISSING_NOTIFICATION_ID); } } @@ -341,8 +354,7 @@ public boolean onKeyDown(int keyCode, KeyEvent event) { } else if (keyCode == KeyEvent.KEYCODE_HOME) { loadHomeScreen(); return true; - } - else { + } else { return super.onKeyDown(keyCode, event); } } @@ -355,14 +367,16 @@ protected void onResume() { Log.d(TAG, "Calling onResume"); } - try { - int locationSetting = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); - if (locationSetting != 0) { - NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); - mNotificationManager.cancel(Constants.LOCATION_DISABLED, Constants.LOCATION_DISABLED_NOTIFICATION_ID); + if (Build.VERSION.SDK_INT >= 19) { + try { + int locationSetting = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.LOCATION_MODE); + if (locationSetting != 0) { + NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); + mNotificationManager.cancel(Constants.LOCATION_DISABLED, Constants.LOCATION_DISABLED_NOTIFICATION_ID); + } + } catch (Settings.SettingNotFoundException e) { + Log.w(TAG, "Location setting is not available on this device"); } - } catch (Settings.SettingNotFoundException e) { - Log.w(TAG, "Location setting is not available on this device"); } boolean isRegistered = Preference.getBoolean(context, Constants.PreferenceFlag.REGISTERED); @@ -413,7 +427,7 @@ protected void onResume() { * Displays an internal server error message to the user. */ private void displayInternalServerError() { - alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, + AlertDialog.Builder alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, getResources().getString(R.string.title_head_connection_error), getResources().getString(R.string.error_internal_server), getResources().getString(R.string.button_ok), @@ -476,6 +490,7 @@ public void onReceiveAPIResult(Map result, int requestCode) { */ private void loadHomeScreen() { + finish(); Intent i = new Intent(); i.setAction(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); diff --git a/client/client/src/main/java/org/wso2/iot/agent/AuthenticationActivity.java b/client/client/src/main/java/org/wso2/iot/agent/AuthenticationActivity.java index b554658a..bcc173c5 100644 --- a/client/client/src/main/java/org/wso2/iot/agent/AuthenticationActivity.java +++ b/client/client/src/main/java/org/wso2/iot/agent/AuthenticationActivity.java @@ -29,6 +29,7 @@ import android.content.pm.PackageManager; import android.os.Build; import android.os.Bundle; +import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.text.Editable; import android.text.TextWatcher; @@ -92,40 +93,42 @@ public class AuthenticationActivity extends SherlockActivity implements APIAcces private EditText etDomain; private EditText etPassword; private RadioButton radioBYOD; - private RadioButton radioCOPE; private String deviceType; private Context context; private String username; private String usernameVal; private String passwordVal; - private TextView textViewWipeData; private ProgressDialog progressDialog; - private LinearLayout loginLayout; private boolean isReLogin = false; private boolean isCloudLogin = false; private DeviceInfo deviceInfo; private static final String TAG = AuthenticationActivity.class.getSimpleName(); private static final String[] SUBSCRIBED_API = new String[]{"android"}; - private ClientAuthenticator authenticator; private Tenant currentTenant; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); + context = this; + + if (Constants.DEFAULT_HOST == null && Preference.getString(context, Constants.PreferenceFlag.IP) == null) { + Intent intent = new Intent(AuthenticationActivity.this, AlreadyRegisteredActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); + finish(); + return; + } + setContentView(R.layout.activity_authentication); getSupportActionBar().setDisplayShowCustomEnabled(true); getSupportActionBar().setCustomView(R.layout.custom_sherlock_bar); getSupportActionBar().setTitle(Constants.EMPTY_STRING); - context = this; deviceInfo = new DeviceInfo(context); etDomain = (EditText) findViewById(R.id.etDomain); etUsername = (EditText) findViewById(R.id.etUsername); etPassword = (EditText) findViewById(R.id.etPassword); - radioBYOD = (RadioButton) findViewById(R.id.radioBYOD); - radioCOPE = (RadioButton) findViewById(R.id.radioCOPE); - loginLayout = (LinearLayout) findViewById(R.id.errorLayout); etDomain.setFocusable(true); etDomain.requestFocus(); btnSignIn = (Button) findViewById(R.id.btnSignIn); @@ -135,8 +138,10 @@ protected void onCreate(Bundle savedInstanceState) { // change button color background till user enters a valid input btnSignIn.setBackground(getResources().getDrawable(R.drawable.btn_grey)); btnSignIn.setTextColor(getResources().getColor(R.color.black)); - + radioBYOD = (RadioButton) findViewById(R.id.radioBYOD); + RadioButton radioCOPE = (RadioButton) findViewById(R.id.radioCOPE); TextView textViewSignIn = (TextView) findViewById(R.id.textViewSignIn); + LinearLayout loginLayout = (LinearLayout) findViewById(R.id.errorLayout); if (Preference.hasPreferenceKey(context, Constants.TOKEN_EXPIRED)) { etDomain.setEnabled(false); @@ -160,6 +165,14 @@ protected void onCreate(Bundle savedInstanceState) { textViewSignIn.setText(R.string.txt_sign_in_cloud); } + if (Preference.getBoolean(context, Constants.PreferenceFlag.DEVICE_ACTIVE) && !isReLogin) { + Intent intent = new Intent(AuthenticationActivity.this, AlreadyRegisteredActivity.class); + intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); + startActivity(intent); + finish(); + return; + } + TextView textViewSignUp = (TextView) findViewById(R.id.textViewSignUp); if (!isReLogin && Constants.SIGN_UP_URL != null) { Linkify.TransformFilter transformFilter = new Linkify.TransformFilter() { @@ -178,14 +191,14 @@ public String transformUrl(Matcher match, String url) { loginLayout.setVisibility(View.GONE); } - if (Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU) { + if (Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP)) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { startLockTask(); } } - textViewWipeData = (TextView) this.findViewById(R.id.textViewWipeData); - if(Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU && Constants.DISPLAY_WIPE_DEVICE_BUTTON){ + TextView textViewWipeData = (TextView) this.findViewById(R.id.textViewWipeData); + if(Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP) && Constants.DISPLAY_WIPE_DEVICE_BUTTON){ textViewWipeData.setVisibility(View.VISIBLE); textViewWipeData.setOnClickListener(new OnClickListener() { @Override @@ -197,9 +210,14 @@ public void onClick(View view) { public void onClick(DialogInterface dialog, int whichButton) { DevicePolicyManager devicePolicyManager = (DevicePolicyManager) getApplicationContext().getSystemService(Context.DEVICE_POLICY_SERVICE); - devicePolicyManager. - wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE | - DevicePolicyManager.WIPE_RESET_PROTECTION_DATA); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) { + devicePolicyManager. + wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE | + DevicePolicyManager.WIPE_RESET_PROTECTION_DATA); + } else { + devicePolicyManager. + wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE); + } }}) .setNegativeButton(android.R.string.no, null) .show(); @@ -243,7 +261,7 @@ public void afterTextChanged(Editable s) { equals(org.wso2.iot.agent.proxy.utils.Constants.Authenticator.MUTUAL_SSL_AUTHENTICATOR)) { AuthenticatorFactory authenticatorFactory = new AuthenticatorFactory(); - authenticator = authenticatorFactory.getClient( + ClientAuthenticator authenticator = authenticatorFactory.getClient( org.wso2.iot.agent.proxy.utils.Constants.Authenticator.AUTHENTICATOR_IN_USE, AuthenticationActivity.this, Constants.AUTHENTICATION_REQUEST_CODE); authenticator.doAuthenticate(); @@ -270,12 +288,21 @@ public void afterTextChanged(Editable s) { // This is added so that in case due to an agent customisation, if the authentication // activity is called the AUTO_ENROLLMENT_BACKGROUND_SERVICE_ENABLED is set, the activity // must be finished. - if (Constants.AUTO_ENROLLMENT_BACKGROUND_SERVICE_ENABLED == true) { + if (Constants.AUTO_ENROLLMENT_BACKGROUND_SERVICE_ENABLED) { finish(); } } + @Override + protected void onDestroy(){ + super.onDestroy(); + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.dismiss(); + progressDialog = null; + } + } + private OnClickListener onClickAuthenticate = new OnClickListener() { @Override @@ -418,7 +445,6 @@ private void startAuthentication() { if (CommonUtils.isNetworkAvailable(context)) { String clientId = Preference.getString(context, Constants.CLIENT_ID); String clientSecret = Preference.getString(context, Constants.CLIENT_SECRET); - String clientName; if (clientId == null || clientSecret == null) { String clientCredentials = Preference.getString(context, getResources().getString(R.string.shared_pref_client_credentials)); @@ -649,7 +675,9 @@ private void checkManifestPermissions(){ } @Override - public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { + public void onRequestPermissionsResult(int requestCode, + @NonNull String[] permissions, + @NonNull int[] grantResults) { if(requestCode == 110){ getConfigurationsFromServer(); } @@ -911,13 +939,13 @@ public void onClick(DialogInterface dialog, int id) { * @param message Message text to be shown as the license. * @param title Title of the license. */ - private void showAgreement(final String message, String title) { + private void showAgreement(final String message, final String title) { AuthenticationActivity.this.runOnUiThread(new Runnable() { @Override public void run() { final Dialog dialog = new Dialog(context); dialog.setContentView(R.layout.custom_terms_popup); - dialog.setTitle(Constants.EULA_TITLE); + dialog.setTitle(title); dialog.setCancelable(false); WebView webView = (WebView) dialog.findViewById(R.id.webview); @@ -1165,9 +1193,6 @@ public void run() { /** * This method is used to retrieve consumer-key and consumer-secret. - * - * @return JSON formatted string. - * @throws AndroidAgentException */ private void getClientCredentials() { String ipSaved = Constants.DEFAULT_HOST; diff --git a/client/client/src/main/java/org/wso2/iot/agent/RegistrationActivity.java b/client/client/src/main/java/org/wso2/iot/agent/RegistrationActivity.java index fe431e5c..f876fee2 100644 --- a/client/client/src/main/java/org/wso2/iot/agent/RegistrationActivity.java +++ b/client/client/src/main/java/org/wso2/iot/agent/RegistrationActivity.java @@ -17,25 +17,11 @@ */ package org.wso2.iot.agent; -import java.util.Map; -import org.wso2.iot.agent.api.DeviceInfo; -import org.wso2.iot.agent.beans.ServerConfig; -import org.wso2.iot.agent.proxy.interfaces.APIResultCallBack; -import org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS; -import org.wso2.iot.agent.services.DeviceInfoPayload; -import org.wso2.iot.agent.utils.CommonDialogUtils; -import org.wso2.iot.agent.utils.Constants; -import org.wso2.iot.agent.utils.FCMRegistrationUtil; -import org.wso2.iot.agent.utils.Preference; -import org.wso2.iot.agent.utils.CommonUtils; - import android.app.Activity; -import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; -import android.content.res.Resources; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; @@ -44,17 +30,27 @@ import com.google.firebase.iid.FirebaseInstanceId; +import org.wso2.iot.agent.api.DeviceInfo; +import org.wso2.iot.agent.beans.ServerConfig; +import org.wso2.iot.agent.proxy.interfaces.APIResultCallBack; +import org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS; +import org.wso2.iot.agent.services.DeviceInfoPayload; +import org.wso2.iot.agent.utils.CommonDialogUtils; +import org.wso2.iot.agent.utils.CommonUtils; +import org.wso2.iot.agent.utils.Constants; +import org.wso2.iot.agent.utils.FCMRegistrationUtil; +import org.wso2.iot.agent.utils.Preference; + +import java.util.Map; + /** * Activity which handles user enrollment. */ public class RegistrationActivity extends Activity implements APIResultCallBack { private Context context; private ProgressDialog progressDialog; - private AlertDialog.Builder alertDialog; private DeviceInfoPayload deviceInfoBuilder; - private Resources resources; - private String deviceIdentifier; - private String TAG = RegistrationActivity.class.getSimpleName(); + private String TAG = RegistrationActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { @@ -72,9 +68,8 @@ public void run() { } }); deviceInfoBuilder = new DeviceInfoPayload(context); - resources = context.getResources(); DeviceInfo deviceInfo = new DeviceInfo(context); - deviceIdentifier = deviceInfo.getDeviceId(); + String deviceIdentifier = deviceInfo.getDeviceId(); Preference.putString(context, Constants.PreferenceFlag.REG_ID, deviceIdentifier); // If the notification type is gcm, before registering the device, make sure that particular device has google @@ -97,6 +92,15 @@ public void run() { } + @Override + protected void onDestroy(){ + super.onDestroy(); + if (progressDialog != null && progressDialog.isShowing()) { + progressDialog.dismiss(); + progressDialog = null; + } + } + private void registerDevice() { String type = Preference.getString(context, context.getResources().getString(R.string.shared_pref_reg_type)); @@ -163,7 +167,7 @@ public boolean onOptionsItemSelected(MenuItem item) { return super.onOptionsItemSelected(item); } - private DialogInterface.OnClickListener registrationFailedOKBtnClickListerner = + private DialogInterface.OnClickListener registrationFailedOKBanClickListener = new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, @@ -182,6 +186,7 @@ private void loadAlreadyRegisteredActivity(){ intent.putExtra(getResources().getString(R.string.intent_extra_fresh_reg_flag), true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); + finish(); } private void loadKioskActivity(){ @@ -190,6 +195,7 @@ private void loadKioskActivity(){ intent.putExtra(getResources().getString(R.string.intent_extra_fresh_reg_flag), true); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); + finish(); } /** @@ -199,11 +205,11 @@ private void displayConnectionError(){ RegistrationActivity.this.runOnUiThread(new Runnable() { @Override public void run() { - alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, - getResources().getString(R.string.title_head_connection_error), - getResources().getString(R.string.error_internal_server), - getResources().getString(R.string.button_ok), - registrationFailedOKBtnClickListerner); + CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, + getResources().getString(R.string.title_head_connection_error), + getResources().getString(R.string.error_internal_server), + getResources().getString(R.string.button_ok), + registrationFailedOKBanClickListener); } }); } @@ -215,11 +221,11 @@ private void displayInternalServerError(){ RegistrationActivity.this.runOnUiThread(new Runnable() { @Override public void run() { - alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, - getResources().getString(R.string.title_head_registration_error), - getResources().getString(R.string.error_for_all_unknown_registration_failures), - getResources().getString(R.string.button_ok), - registrationFailedOKBtnClickListerner); + CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, + getResources().getString(R.string.title_head_registration_error), + getResources().getString(R.string.error_for_all_unknown_registration_failures), + getResources().getString(R.string.button_ok), + registrationFailedOKBanClickListener); } }); } @@ -230,10 +236,10 @@ public void run() { private void displayGooglePlayServicesError() { RegistrationActivity.this.runOnUiThread(new Runnable() { @Override public void run() { - alertDialog = CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, + CommonDialogUtils.getAlertDialogWithOneButtonAndTitle(context, getResources().getString(R.string.title_head_registration_error), getResources().getString(R.string.error_for_gcm_unavailability), - getResources().getString(R.string.button_ok), registrationFailedOKBtnClickListerner); + getResources().getString(R.string.button_ok), registrationFailedOKBanClickListener); } }); } @@ -251,7 +257,7 @@ public void onReceiveAPIResult(Map result, int requestCode) { registerGCM(); } else { CommonDialogUtils.stopProgressDialog(progressDialog); - if(Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU){ + if(Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP)){ loadKioskActivity(); }else{ loadAlreadyRegisteredActivity(); @@ -265,10 +271,10 @@ public void onReceiveAPIResult(Map result, int requestCode) { } } else if (Constants.POLICY_REQUEST_CODE == requestCode) { CommonDialogUtils.stopProgressDialog(progressDialog); - if(Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU){ + if (Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP)) { loadKioskActivity(); finish(); - }else{ + } else { loadAlreadyRegisteredActivity(); } } else if (requestCode == Constants.GCM_REGISTRATION_ID_SEND_CODE && result != null) { @@ -277,9 +283,9 @@ public void onReceiveAPIResult(Map result, int requestCode) { displayConnectionError(); } else { CommonDialogUtils.stopProgressDialog(progressDialog); - if(Constants.DEFAULT_OWNERSHIP == Constants.OWNERSHIP_COSU){ + if (Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP)) { loadKioskActivity(); - }else{ + } else { loadAlreadyRegisteredActivity(); } } @@ -359,6 +365,4 @@ private void loadAuthenticationErrorActivity() { finish(); } - - } diff --git a/client/client/src/main/java/org/wso2/iot/agent/services/AgentDeviceAdminReceiver.java b/client/client/src/main/java/org/wso2/iot/agent/services/AgentDeviceAdminReceiver.java index ed19729b..f97ed1de 100644 --- a/client/client/src/main/java/org/wso2/iot/agent/services/AgentDeviceAdminReceiver.java +++ b/client/client/src/main/java/org/wso2/iot/agent/services/AgentDeviceAdminReceiver.java @@ -17,7 +17,15 @@ */ package org.wso2.iot.agent.services; -import java.util.Map; +import android.annotation.TargetApi; +import android.app.admin.DeviceAdminReceiver; +import android.app.admin.DevicePolicyManager; +import android.content.ComponentName; +import android.content.Context; +import android.content.Intent; +import android.os.Build; +import android.util.Log; +import android.widget.Toast; import org.wso2.iot.agent.AndroidAgentException; import org.wso2.iot.agent.R; @@ -25,20 +33,11 @@ import org.wso2.iot.agent.beans.ServerConfig; import org.wso2.iot.agent.proxy.interfaces.APIResultCallBack; import org.wso2.iot.agent.proxy.utils.Constants.HTTP_METHODS; +import org.wso2.iot.agent.utils.CommonUtils; import org.wso2.iot.agent.utils.Constants; import org.wso2.iot.agent.utils.Preference; -import org.wso2.iot.agent.utils.CommonUtils; -import android.annotation.TargetApi; -import android.app.admin.DeviceAdminReceiver; -import android.app.admin.DevicePolicyManager; -import android.content.ComponentName; -import android.content.Context; -import android.content.Intent; -import android.content.res.Resources; -import android.os.Build; -import android.util.Log; -import android.widget.Toast; +import java.util.Map; /** * This is the component that is responsible for actual device administration. @@ -49,8 +48,6 @@ public class AgentDeviceAdminReceiver extends DeviceAdminReceiver implements APIResultCallBack { private static final String TAG = AgentDeviceAdminReceiver.class.getName(); - private String regId; - private static final int ACTIVATION_REQUEST = 47; public static final String DISALLOW_SAFE_BOOT = "no_safe_boot"; /** @@ -76,10 +73,11 @@ public void onEnabled(final Context context, Intent intent) { public void onDisabled(Context context, Intent intent) { super.onDisabled(context, intent); + Preference.putBoolean(context, Constants.PreferenceFlag.DEVICE_ACTIVE, false); if (!Constants.OWNERSHIP_COSU.equals(Constants.DEFAULT_OWNERSHIP)) { Toast.makeText(context, R.string.device_admin_disabled, Toast.LENGTH_LONG).show(); - regId = Preference + String regId = Preference .getString(context, Constants.PreferenceFlag.REG_ID); if (regId != null && !regId.isEmpty()) { startUnRegistration(context); diff --git a/client/client/src/main/java/org/wso2/iot/agent/services/location/LocationService.java b/client/client/src/main/java/org/wso2/iot/agent/services/location/LocationService.java index dd81c749..d3282bac 100644 --- a/client/client/src/main/java/org/wso2/iot/agent/services/location/LocationService.java +++ b/client/client/src/main/java/org/wso2/iot/agent/services/location/LocationService.java @@ -22,7 +22,6 @@ import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; -import android.location.Criteria; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; @@ -40,6 +39,7 @@ import org.wso2.iot.agent.utils.CommonUtils; import org.wso2.iot.agent.utils.Constants; +import java.util.ArrayList; import java.util.List; /** @@ -51,9 +51,9 @@ public class LocationService extends Service implements LocationListener { private LocationManager locationManager = null; private Context context; - private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 100; - private static final long MIN_TIME_BW_UPDATES = 1000 * 60; - private String provider = null; + private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; //If more than 10Km + private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 15; //If more than 15 minutes + private List providers = new ArrayList<>(); private boolean isUpdateRequested = false; private final IBinder mBinder = new LocalBinder(); @@ -97,14 +97,16 @@ public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; } Location location = null; + long locationTime = 0; //We are trying for all enabled providers - List providers = locationManager.getProviders(true); - for (String p : providers) { - location = locationManager.getLastKnownLocation(p); - if (location != null) { - break; + List _providers = locationManager.getProviders(true); + for (String p : _providers) { + Location l = locationManager.getLastKnownLocation(p); + if (l != null && l.getTime() > locationTime) { + locationTime = l.getTime(); + location = l; } else if (Constants.DEBUG_MODE_ENABLED) { - Log.d(TAG, "No last known location found for provider " + p); + Log.d(TAG, "Last known location from provider " + p + " is not found or too old."); } } if (location != null) { @@ -167,20 +169,18 @@ private void setLocation() { displayPermissionMissingNotification(); return; } - Criteria criteria = new Criteria(); - criteria.setAccuracy(Criteria.ACCURACY_FINE); - criteria.setAltitudeRequired(false); - criteria.setBearingRequired(false); - provider = locationManager.getBestProvider(criteria, true); - if (provider != null) { + providers = locationManager.getProviders(true); + if (providers != null && !providers.isEmpty()) { if (isUpdateRequested) { locationManager.removeUpdates(this); } - if (Constants.DEBUG_MODE_ENABLED) { - Log.d(TAG, "Requesting locations from provider: " + provider); + for (String provider : providers) { + if (Constants.DEBUG_MODE_ENABLED) { + Log.d(TAG, "Requesting locations from provider: " + provider); + } + locationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, + MIN_DISTANCE_CHANGE_FOR_UPDATES, this); } - locationManager.requestLocationUpdates(provider, MIN_TIME_BW_UPDATES, - MIN_DISTANCE_CHANGE_FOR_UPDATES, this); isUpdateRequested = true; } else { Log.w(TAG, "No suitable location providers found"); @@ -229,7 +229,7 @@ public void onProviderDisabled(String provider) { if (Constants.DEBUG_MODE_ENABLED) { Log.d(TAG, "Provider disabled: " + provider); } - if (this.provider != null && this.provider.equals(provider)) { + if (providers.contains(provider) && locationManager != null) { setLocation(); } } diff --git a/client/iDPProxy/src/main/AndroidManifest.xml b/client/iDPProxy/src/main/AndroidManifest.xml index 814a4c4f..68091701 100644 --- a/client/iDPProxy/src/main/AndroidManifest.xml +++ b/client/iDPProxy/src/main/AndroidManifest.xml @@ -21,6 +21,4 @@ android:versionCode="1" android:versionName="1.0" > - - diff --git a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/AccessTokenHandler.java b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/AccessTokenHandler.java index bb77ce2e..b5a85b12 100644 --- a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/AccessTokenHandler.java +++ b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/AccessTokenHandler.java @@ -21,6 +21,7 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; + import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; @@ -29,6 +30,7 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; + import org.apache.commons.codec.binary.Base64; import org.json.JSONException; import org.json.JSONObject; @@ -38,11 +40,8 @@ import org.wso2.iot.agent.proxy.utils.Constants; import org.wso2.iot.agent.proxy.utils.ServerUtilities; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; -import java.util.Locale; import java.util.Map; /** @@ -70,7 +69,7 @@ public AccessTokenHandler(CredentialInfo info, CallBack callBack) { * token as a result */ public void obtainAccessToken() { - RequestQueue queue = null; + RequestQueue queue; if(Constants.DEBUG_ENABLED) { Log.d(TAG, "Fetching a new tokens."); } @@ -78,6 +77,7 @@ public void obtainAccessToken() { queue = ServerUtilities.getCertifiedHttpClient(); } catch (IDPTokenManagerException e) { Log.e(TAG, "Failed to retrieve HTTP client", e); + return; } StringRequest request = new StringRequest(Request.Method.POST, info.getTokenEndPoint(), @@ -188,7 +188,7 @@ private void processTokenResponse(String responseCode, String result) { editor.putString(Constants.REFRESH_TOKEN, refreshToken); editor.putString(USERNAME_LABEL, info.getUsername()); editor.putLong(Constants.EXPIRE_TIME, expiresOn); - editor.commit(); + editor.apply(); identityProxy.receiveAccessToken(responseCode, Constants.SUCCESS_RESPONSE, token); } catch (JSONException e) { diff --git a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/IdentityProxy.java b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/IdentityProxy.java index a8f0deba..85207337 100644 --- a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/IdentityProxy.java +++ b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/IdentityProxy.java @@ -18,11 +18,9 @@ package org.wso2.iot.agent.proxy; import android.content.Context; -import android.content.Intent; import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; -import android.widget.Toast; import org.wso2.iot.agent.proxy.beans.CredentialInfo; import org.wso2.iot.agent.proxy.beans.Token; @@ -116,7 +114,7 @@ public void init(CredentialInfo info, APIAccessCallBack apiAccessCallBack, Conte editor.putString(Constants.CLIENT_ID, clientID); editor.putString(Constants.CLIENT_SECRET, clientSecret); editor.putString(Constants.TOKEN_ENDPOINT, info.getTokenEndPoint()); - editor.commit(); + editor.apply(); setAccessTokenURL(info.getTokenEndPoint()); AccessTokenHandler accessTokenHandler = new AccessTokenHandler(info, this); accessTokenHandler.obtainAccessToken(); diff --git a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/RefreshTokenHandler.java b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/RefreshTokenHandler.java index aec37109..eda87c55 100644 --- a/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/RefreshTokenHandler.java +++ b/client/iDPProxy/src/main/java/org/wso2/iot/agent/proxy/RefreshTokenHandler.java @@ -22,6 +22,7 @@ import android.content.SharedPreferences; import android.content.SharedPreferences.Editor; import android.util.Log; + import com.android.volley.AuthFailureError; import com.android.volley.DefaultRetryPolicy; import com.android.volley.NetworkResponse; @@ -30,6 +31,7 @@ import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; + import org.apache.commons.codec.binary.Base64; import org.json.JSONException; import org.json.JSONObject; @@ -37,11 +39,8 @@ import org.wso2.iot.agent.proxy.utils.Constants; import org.wso2.iot.agent.proxy.utils.ServerUtilities; -import java.text.DateFormat; -import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; -import java.util.Locale; import java.util.Map; /** @@ -69,6 +68,7 @@ public void obtainNewAccessToken() { queue = ServerUtilities.getCertifiedHttpClient(); } catch (IDPTokenManagerException e) { Log.e(TAG, "Failed to retrieve HTTP client", e); + return; } StringRequest request = new StringRequest(Request.Method.POST, IdentityProxy.getInstance().getAccessTokenURL(), @@ -159,7 +159,7 @@ private void processTokenResponse(String responseCode, String result) { editor.putString(Constants.ACCESS_TOKEN, accessToken); editor.putString(Constants.REFRESH_TOKEN, refreshToken); editor.putLong(Constants.EXPIRE_TIME, expiresOn); - editor.commit(); + editor.apply(); identityProxy .receiveNewAccessToken(responseCode, Constants.SUCCESS_RESPONSE, token);