From e9c4aef12c37c4c34d25a636101131f50673187f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mieszko=20Wrzeszczy=C5=84ski?= Date: Sun, 14 Oct 2018 12:46:33 +0200 Subject: [PATCH] Improve background-task & fetch user profile after logging --- app/build.gradle | 2 +- .../findmytutor/activity/LoginActivity.java | 52 ++++- .../findmytutor/activity/MainActivity.java | 87 +++---- .../uam/wmi/findmytutor/model/Coordinate.java | 5 +- .../BackgroundLocalizationService.java | 213 +++++++----------- .../utils/BroadcastLocalizationHandler.java | 104 --------- .../uam/wmi/findmytutor/utils/PrefUtils.java | 43 +++- .../wmi/findmytutor/utils/RestApiHelper.java | 20 ++ 8 files changed, 220 insertions(+), 306 deletions(-) delete mode 100644 app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java create mode 100644 app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java diff --git a/app/build.gradle b/app/build.gradle index 8538ba4..595676b 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -8,7 +8,7 @@ android { } defaultConfig { applicationId "com.uam.wmi.findmytutor" - minSdkVersion 23 + minSdkVersion 22 targetSdkVersion 27 versionCode 1 versionName "1.0" diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java index bc64274..9047291 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/LoginActivity.java @@ -33,12 +33,16 @@ import android.widget.ToggleButton; import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.JWT; +import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.uam.wmi.findmytutor.R; import com.uam.wmi.findmytutor.model.JwtToken; import com.uam.wmi.findmytutor.model.LdapUser; +import com.uam.wmi.findmytutor.model.User; import com.uam.wmi.findmytutor.network.ApiClient; import com.uam.wmi.findmytutor.service.LdapService; +import com.uam.wmi.findmytutor.service.UserService; import com.uam.wmi.findmytutor.utils.PrefUtils; +import com.uam.wmi.findmytutor.utils.RestApiHelper; import java.util.ArrayList; import java.util.List; @@ -47,6 +51,7 @@ import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.schedulers.Schedulers; +import okhttp3.ResponseBody; import static android.Manifest.permission.READ_CONTACTS; @@ -326,6 +331,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< private final String mPassword; private boolean isTutor; private LdapService ldapService; + private UserService userService; private CompositeDisposable disposable = new CompositeDisposable(); private Boolean isAuthorizate; @@ -334,16 +340,52 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< mEmail = email; mPassword = password; isTutor = loginOption; - this.ldapService = ApiClient.getClient(getApplicationContext()) + isAuthorizate = false; + ldapService = ApiClient.getClient(getApplicationContext()) .create(LdapService.class); - this.isAuthorizate = false; + userService = ApiClient.getClient(getApplicationContext()) + .create(UserService.class); PrefUtils.storeIsTutor(getApplicationContext(), this.isTutor); } + private void saveUserProfileToSharedPreferences(User user){ + PrefUtils.storeUserFirstName(getApplicationContext(), user.getFirstName()); + PrefUtils.storeUserLastName(getApplicationContext(), user.getLastName()); + PrefUtils.storeUserName(getApplicationContext(), user.getUserName()); + } + + private void getUserProfile(String userId) { + disposable.add( + userService + .getUserByID(userId) + .subscribeOn(Schedulers.io()) + .observeOn(AndroidSchedulers.mainThread()) + .subscribeWith(new DisposableSingleObserver() { + @Override + public void onSuccess(User user) { + Log.e("USER", String.valueOf(user)); + saveUserProfileToSharedPreferences(user); + + onPostExecute(true); + } + + public void onError(Throwable e) { + ((HttpException) e).code(); + Log.e("Login onError", e.getMessage()); + + if (e instanceof HttpException) { + ResponseBody responseBody = ((HttpException) e).response().errorBody(); + Log.e("Login onError", RestApiHelper.getErrorMessage(responseBody)); + } + + } + })); + } + @Override protected Boolean doInBackground(Void... params) { - LdapUser user = new LdapUser(mEmail,mPassword,"admin",(isTutor)?"Tutor":"Student","string","string",mEmail); + LdapUser user = new LdapUser(mEmail, mPassword, "admin", (isTutor) ? "Tutor" : "Student", "string", "string", mEmail); disposable.add( ldapService @@ -362,7 +404,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeUserId(getApplicationContext(), role.asString()); - onPostExecute(true); + getUserProfile(role.asString()); } @Override @@ -370,8 +412,8 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks< Log.e("LoginError", "onError: " + e.getMessage()); } })); - return true; + return true; } @Override diff --git a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java index 21000ec..fc1eb86 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/activity/MainActivity.java @@ -3,15 +3,11 @@ package com.uam.wmi.findmytutor.activity; import android.app.Fragment; import android.app.FragmentTransaction; import android.content.Intent; -import android.content.SharedPreferences; -import android.location.Geocoder; - import android.content.res.Configuration; import android.os.Bundle; -import android.support.annotation.NonNull; + import android.support.design.widget.BottomNavigationView; import android.support.design.widget.FloatingActionButton; - import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.AppCompatActivity; @@ -27,22 +23,22 @@ import android.content.pm.PackageManager; import android.os.Build; import android.view.View; -import android.widget.AdapterView; import android.widget.FrameLayout; - -import android.support.v7.widget.Toolbar; import android.widget.ListView; import android.widget.Toast; +import android.support.v7.widget.Toolbar; + import com.mapbox.mapboxsdk.Mapbox; + import com.uam.wmi.findmytutor.ListViewAdapter; import com.uam.wmi.findmytutor.R; -import java.util.ArrayList; -import java.util.Locale; - import com.uam.wmi.findmytutor.service.BackgroundLocalizationService; import com.uam.wmi.findmytutor.utils.PrefUtils; +import java.util.ArrayList; + + public class MainActivity extends AppCompatActivity { private BottomNavigationView mMainNav; @@ -54,10 +50,6 @@ public class MainActivity extends AppCompatActivity { private static final int REQUEST_PERMISSIONS = 100; boolean boolean_permission; - SharedPreferences mPref; - SharedPreferences.Editor medit; - Double latitude, longitude; - Geocoder geocoder; private DrawerLayout drawerLayout; private ActionBarDrawerToggle actionBarDrawerToggle; @@ -79,10 +71,11 @@ public class MainActivity extends AppCompatActivity { configureconfigureNavigationDrawer(); configureBottomNavigationView(); configureLogoutButton(); + } private void configureconfigureNavigationDrawer() { - listView = (ListView) findViewById(R.id.list_item); + listView = findViewById(R.id.list_item); Toolbar toolbar = findViewById(R.id.toolbar_main); setSupportActionBar(toolbar); @@ -90,13 +83,7 @@ public class MainActivity extends AppCompatActivity { adapter = new ListViewAdapter(this, R.layout.item_listview, stringArrayList); listView.setAdapter(adapter); - listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { - @Override - public void onItemClick(AdapterView parent, View view, int position, long id) { - Toast.makeText(MainActivity.this, (String)parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show(); - } - }); - + listView.setOnItemClickListener((parent, view, position, id) -> Toast.makeText(MainActivity.this, (String)parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show()); drawerLayout = findViewById(R.id.drawer_layout); @@ -121,8 +108,8 @@ public class MainActivity extends AppCompatActivity { private void configureBottomNavigationView(){ - mMainFrame = (FrameLayout) findViewById(R.id.main_frame); - mMainNav = (BottomNavigationView) findViewById(R.id.main_nav); + mMainFrame = findViewById(R.id.main_frame); + mMainNav = findViewById(R.id.main_nav); isTutor = PrefUtils.getIsTutor(getApplicationContext()); if (!isTutor) { @@ -138,23 +125,20 @@ public class MainActivity extends AppCompatActivity { mMainNav.setSelectedItemId(R.id.nav_map); /* code below is resposible for changing colours of tabs in main tab menu */ - mMainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { - @Override - public boolean onNavigationItemSelected(@NonNull MenuItem item) { + mMainNav.setOnNavigationItemSelectedListener(item -> { - switch (item.getItemId()) { - case R.id.nav_map: - setFragment(mapFragment); - return true; - case R.id.nav_notif: - setFragment(notificationFragment); - return true; - case R.id.nav_profile: - setFragment(profileFragment); - return true; - default: - return false; - } + switch (item.getItemId()) { + case R.id.nav_map: + setFragment(mapFragment); + return true; + case R.id.nav_notif: + setFragment(notificationFragment); + return true; + case R.id.nav_profile: + setFragment(profileFragment); + return true; + default: + return false; } }); } @@ -163,19 +147,16 @@ public class MainActivity extends AppCompatActivity { // Logout button final FloatingActionButton button = findViewById(R.id.logoutButton); - button.setOnClickListener(new View.OnClickListener() { - @Override - public void onClick(View view) { - PrefUtils.cleanUserLocalStorage(getApplicationContext()); + button.setOnClickListener(view -> { + PrefUtils.cleanUserLocalStorage(getApplicationContext()); - Intent i = getBaseContext().getPackageManager() - .getLaunchIntentForPackage(getBaseContext().getPackageName()); - if (i != null) { - i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); - } - startActivity(i); - finish(); + Intent i = getBaseContext().getPackageManager() + .getLaunchIntentForPackage(getBaseContext().getPackageName()); + if (i != null) { + i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); } + startActivity(i); + finish(); }); } @@ -230,8 +211,6 @@ public class MainActivity extends AppCompatActivity { protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); - - // Sync the toggle state after onRestoreInstanceState has occurred. actionBarDrawerToggle.syncState(); if (isTutor) { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java index a83053a..2280dd4 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/model/Coordinate.java @@ -44,14 +44,15 @@ public class Coordinate extends BaseResponse { @SerializedName("label") private String label; - public Coordinate (Double latitude, Double longitude, String label, String userId) { + public Coordinate (Double latitude, Double longitude, Double altitude, String label, String userId) { //if (!latitudeRange.contains(latitude)) throw new IllegalArgumentException("Inappropriate latitude value" + latitude); //if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude); this.latitude = latitude; this.longitude = longitude; - this.userId = userId; + this.altitude = altitude; this.label = label; + this.userId = userId; } public Coordinate (Double latitude) { diff --git a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java index 0f1dc6c..af7e14e 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/service/BackgroundLocalizationService.java @@ -26,11 +26,16 @@ import com.jakewharton.retrofit2.adapter.rxjava2.HttpException; import com.uam.wmi.findmytutor.model.Coordinate; import com.uam.wmi.findmytutor.network.ApiClient; import com.uam.wmi.findmytutor.utils.PrefUtils; +import com.uam.wmi.findmytutor.utils.RestApiHelper; import org.json.JSONObject; import java.io.IOException; +import java.io.InterruptedIOException; +import java.lang.reflect.Array; import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.List; import java.util.Timer; import java.util.TimerTask; @@ -48,18 +53,14 @@ public class BackgroundLocalizationService extends Service { private LocationManager mLocationManager = null; private static final int LOCATION_INTERVAL = 1000; private static final float LOCATION_DISTANCE = 10f; - private Handler mHandler = new Handler(); private static long notify_interval = 10000; - - double latitude, longitude; - boolean isGPSEnable = false; - boolean isNetworkEnable = false; + private Handler mHandler = new Handler(); Location mLastLocation; Intent intent; - LocationManager locationManager; - Location location; + ArrayList providers = new ArrayList(); + LocationListener[] mLocationListeners ; private class LocationListener implements android.location.LocationListener { @@ -91,12 +92,6 @@ public class BackgroundLocalizationService extends Service { } } - LocationListener[] mLocationListeners = new LocationListener[]{ - new LocationListener(LocationManager.GPS_PROVIDER), - new LocationListener(LocationManager.NETWORK_PROVIDER), - //new LocationListener(LocationManager.PASSIVE_PROVIDER) - }; - @Override public IBinder onBind(Intent arg0) { return null; @@ -110,9 +105,20 @@ public class BackgroundLocalizationService extends Service { return START_STICKY; } + public BackgroundLocalizationService(){ + providers.add(LocationManager.GPS_PROVIDER); + providers.add(LocationManager.NETWORK_PROVIDER); + providers.add(LocationManager.PASSIVE_PROVIDER); + + mLocationListeners = new LocationListener[]{ + new LocationListener(LocationManager.GPS_PROVIDER), + new LocationListener(LocationManager.NETWORK_PROVIDER), + new LocationListener(LocationManager.PASSIVE_PROVIDER) + }; + } + @Override public void onCreate() { - Log.e(TAG, "onCreate"); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) @@ -121,40 +127,34 @@ public class BackgroundLocalizationService extends Service { Notification notification = new NotificationCompat.Builder(this, "NOTIFICATION_CHANNEL") .setContentText("Content").build(); startForeground(1001, notification); - } initializeLocationManager(); - try { - mLocationManager.requestLocationUpdates( - LocationManager.PASSIVE_PROVIDER, - LOCATION_INTERVAL, - LOCATION_DISTANCE, - mLocationListeners[0] - ); - } catch (java.lang.SecurityException ex) { - Log.i(TAG, "fail to request location update, ignore", ex); - } catch (IllegalArgumentException ex) { - Log.d(TAG, "network provider does not exist, " + ex.getMessage()); + Integer providerIndex = 0; + + for (LocationListener listener : mLocationListeners) { + try { + mLocationManager.requestLocationUpdates( + providers.get(providerIndex), + LOCATION_INTERVAL, + LOCATION_DISTANCE, + listener + ); + } catch (java.lang.SecurityException ex) { + Log.i(TAG, "fail to request location update, ignore", ex); + } catch (IllegalArgumentException ex) { + Log.d(TAG, "network provider does not exist, " + ex.getMessage()); + } + + providerIndex++; } - try { - mLocationManager.requestLocationUpdates( - LocationManager.GPS_PROVIDER, - LOCATION_INTERVAL, - LOCATION_DISTANCE, - mLocationListeners[1] - ); - } catch (java.lang.SecurityException ex) { - Log.i(TAG, "fail to request location update, ignore", ex); - } catch (IllegalArgumentException ex) { - Log.d(TAG, "gps provider does not exist " + ex.getMessage()); - } Timer mTimer = new Timer(); mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval); intent = new Intent(str_receiver); + fn_getlocation(); } @RequiresApi(api = Build.VERSION_CODES.O) @@ -180,80 +180,35 @@ public class BackgroundLocalizationService extends Service { private void fn_getlocation() { - locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); - isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); - isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); - - if (!isGPSEnable && !isNetworkEnable) { - - } else { - - - if (isGPSEnable) { - location = null; - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. - return; - } - locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, mLocationListeners[1]); - if (locationManager != null) { - location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); - if (location != null) { - latitude = location.getLatitude(); - longitude = location.getLongitude(); - - fn_update(location); - } - } - } - - if (isNetworkEnable) { - location = null; - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. - return; - } - - locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, mLocationListeners[0]); - - if (locationManager != null) { - if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { - // TODO: Consider calling - // ActivityCompat#requestPermissions - // here to request the missing permissions, and then overriding - // public void onRequestPermissionsResult(int requestCode, String[] permissions, - // int[] grantResults) - // to handle the case where the user grants the permission. See the documentation - // for ActivityCompat#requestPermissions for more details. - return; - } - location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); - if (location != null) { - latitude = location.getLatitude(); - longitude = location.getLongitude(); - fn_update(location); - } - } - - } - - + if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { + // TODO: Consider calling + // ActivityCompat#requestPermissions + // here to request the missing permissions, and then overriding + // public void onRequestPermissionsResult(int requestCode, String[] permissions, + // int[] grantResults) + // to handle the case where the user grants the permission. See the documentation + // for ActivityCompat#requestPermissions for more details. + return; } - } + List providers1 = mLocationManager.getProviders(true); + Location bestLocation = null; + for (String provider : providers1) { + Location location = mLocationManager.getLastKnownLocation(provider); + if (location == null) { + continue; + } + if (bestLocation == null || location.getAccuracy() < bestLocation.getAccuracy()) { + bestLocation = location; + } + } + + Log.e("Best localization:", String.valueOf(bestLocation)); + + if (bestLocation != null) + fn_update(bestLocation); + } private class TimerTaskToGetLocation extends TimerTask { @Override @@ -263,23 +218,21 @@ public class BackgroundLocalizationService extends Service { } private void fn_update(Location location) { - intent.putExtra("latitude", location.getLatitude()); - intent.putExtra("longitude", location.getLongitude()); - Log.e(TAG, String.valueOf(location)); new Task(location).execute(); } @Override public void onDestroy() { Log.e(TAG, "onDestroy"); + super.onDestroy(); if (mLocationManager != null) { - for (int i = 0; i < mLocationListeners.length; i++) { + for (LocationListener listener : mLocationListeners) { try { if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } - mLocationManager.removeUpdates(mLocationListeners[i]); + mLocationManager.removeUpdates(listener); } catch (Exception ex) { Log.i(TAG, "fail to remove location listener, ignore", ex); } @@ -289,6 +242,7 @@ public class BackgroundLocalizationService extends Service { private void initializeLocationManager() { Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE); + if (mLocationManager == null) { mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); } @@ -297,26 +251,27 @@ public class BackgroundLocalizationService extends Service { private class Task extends AsyncTask { private Double latitude; private Double longitude; + private Double altitude; private CompositeDisposable disposable = new CompositeDisposable(); private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) .create(CoordinateService.class); private Task(Location location) { - this.latitude = location.getLatitude(); - this.longitude = location.getLongitude(); + latitude = location.getLatitude(); + longitude = location.getLongitude(); + altitude = location.getAltitude(); } - @Override protected Object doInBackground(Object[] objects) { try { - Coordinate coordinate = new Coordinate( - this.latitude, - this.longitude, - PrefUtils.getUserStatus(getApplicationContext()), + latitude, + longitude, + altitude, + PrefUtils.getUserFirstName(getApplicationContext()) + " " + PrefUtils.getUserLastName(getApplicationContext()), PrefUtils.getUserId(getApplicationContext()) ); @@ -335,14 +290,14 @@ public class BackgroundLocalizationService extends Service { @SuppressLint("LongLogTag") @Override public void onError(Throwable e) { - ((HttpException) e).code(); + Log.e("CoordinateService onError", e.getMessage()); if (e instanceof HttpException) { - ResponseBody responseBody = ((HttpException)e).response().errorBody(); - Log.e("CoordinateService onError", getErrorMessage(responseBody)); - } + ResponseBody responseBody = ((HttpException) e).response().errorBody(); + Log.e("CoordinateService onError", RestApiHelper.getErrorMessage(responseBody)); + } } })); } catch (IllegalArgumentException e) { @@ -352,14 +307,6 @@ public class BackgroundLocalizationService extends Service { return null; } - private String getErrorMessage(ResponseBody responseBody) { - try { - JSONObject jsonObject = new JSONObject(responseBody.string()); - return jsonObject.getString("message"); - } catch (Exception e) { - return e.getMessage(); - } - } } } \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java deleted file mode 100644 index afd7765..0000000 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/BroadcastLocalizationHandler.java +++ /dev/null @@ -1,104 +0,0 @@ -package com.uam.wmi.findmytutor.utils; - -import android.annotation.SuppressLint; -import android.content.BroadcastReceiver; -import android.content.Context; -import android.content.Intent; -import android.content.IntentFilter; -import android.os.AsyncTask; -import android.support.v4.content.LocalBroadcastManager; -import android.util.ArrayMap; -import android.util.Log; - -import com.auth0.android.jwt.Claim; -import com.auth0.android.jwt.JWT; -import com.uam.wmi.findmytutor.model.Coordinate; -import com.uam.wmi.findmytutor.model.JwtToken; -import com.uam.wmi.findmytutor.model.LdapUser; -import com.uam.wmi.findmytutor.network.ApiClient; -import com.uam.wmi.findmytutor.service.CoordinateService; -import com.uam.wmi.findmytutor.service.LdapService; - -import org.json.JSONObject; -import org.reactivestreams.Subscriber; -import org.reactivestreams.Subscription; - -import java.util.Map; - -import io.reactivex.android.schedulers.AndroidSchedulers; -import io.reactivex.disposables.CompositeDisposable; -import io.reactivex.observers.DisposableObserver; -import io.reactivex.observers.DisposableSingleObserver; -import io.reactivex.schedulers.Schedulers; -import okhttp3.RequestBody; -import okhttp3.ResponseBody; -import retrofit2.Call; -import retrofit2.Callback; -import timber.log.Timber; - -import static android.content.ContentValues.TAG; -import static com.mapbox.mapboxsdk.Mapbox.getApplicationContext; - -public class BroadcastLocalizationHandler extends BroadcastReceiver { - - @Override - public void onReceive(Context arg0, Intent intent) { - final PendingResult pendingResult = goAsync(); - Task asyncTask = new Task(pendingResult, intent); - asyncTask.execute(); - } - - private static class Task extends AsyncTask { - private Double latitude; - private Double longitude; - - private CompositeDisposable disposable = new CompositeDisposable(); - private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) - .create(CoordinateService.class); - - private Task(PendingResult pendingResult, Intent intent) { - this.latitude = intent.getDoubleExtra("latitude", 0); - this.longitude = intent.getDoubleExtra("longitude", 0); - } - - - @Override - protected Object doInBackground(Object[] objects) { - - try { - - Coordinate coordinate = new Coordinate( - this.latitude, - this.longitude, - PrefUtils.getUserStatus(getApplicationContext()), - PrefUtils.getUserId(getApplicationContext()) - ); - - disposable.add( - coordinateService - .postCoordinate(coordinate) - .subscribeOn(Schedulers.io()) - .observeOn(AndroidSchedulers.mainThread()) - .subscribeWith(new DisposableSingleObserver() { - @SuppressLint("LongLogTag") - @Override - public void onSuccess(Coordinate coord) { - Log.e("CoordinateService onSuccess", String.valueOf(coord)); - } - - @Override - public void onError(Throwable e) { - Log.e("LoginError", "onError: " + e.getMessage()); - } - })); - } catch (IllegalArgumentException e) { - Timber.e(String.valueOf(e)); - } - - return null; - } - } -} - - - diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java index 0c6fe6a..93c9065 100644 --- a/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/PrefUtils.java @@ -16,6 +16,12 @@ public class PrefUtils { return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE); } + public static void cleanUserLocalStorage(Context context) { + SharedPreferences preferences = getSharedPreferences(context); + SharedPreferences.Editor editor = preferences.edit(); + editor.clear().apply(); + } + public static void storeApiKey(Context context, String apiKey) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putString("API_KEY", apiKey); @@ -61,13 +67,7 @@ public class PrefUtils { return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false); } - public static void cleanUserLocalStorage(Context context) { - SharedPreferences preferences = getSharedPreferences(context); - SharedPreferences.Editor editor = preferences.edit(); - editor.clear().apply(); - } - - public static void storeIsServiceRunning(Context context, Boolean flag) { + public static void storeIsServiceRunning(Context context, Boolean flag) { SharedPreferences.Editor editor = getSharedPreferences(context).edit(); editor.putBoolean("IS_SERVIS_RUNNING", flag); editor.apply(); @@ -77,5 +77,34 @@ public class PrefUtils { return getSharedPreferences(context).getBoolean("IS_SERVIS_RUNNING", false); } + public static void storeUserFirstName(Context context, String userName) { + SharedPreferences.Editor editor = getSharedPreferences(context).edit(); + editor.putString("USER_FIRST_NAME", userName); + editor.apply(); + } + + public static String getUserFirstName(Context context) { + return getSharedPreferences(context).getString("USER_FIRST_NAME", null); + } + + public static void storeUserLastName(Context context, String userLastName) { + SharedPreferences.Editor editor = getSharedPreferences(context).edit(); + editor.putString("USER_LAST_NAME", userLastName); + editor.apply(); + } + + public static String getUserLastName(Context context) { + return getSharedPreferences(context).getString("USER_LAST_NAME", null); + } + + public static void storeUserName(Context context, String userName) { + SharedPreferences.Editor editor = getSharedPreferences(context).edit(); + editor.putString("USER_NAME", userName); + editor.apply(); + } + + public static String getUserName(Context context) { + return getSharedPreferences(context).getString("USER_NAME", null); + } } \ No newline at end of file diff --git a/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java b/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java new file mode 100644 index 0000000..ec27e2c --- /dev/null +++ b/app/src/main/java/com/uam/wmi/findmytutor/utils/RestApiHelper.java @@ -0,0 +1,20 @@ +package com.uam.wmi.findmytutor.utils; + +import org.json.JSONObject; + +import okhttp3.ResponseBody; + +public class RestApiHelper { + + public RestApiHelper() { + } + + public static String getErrorMessage(ResponseBody responseBody) { + try { + JSONObject jsonObject = new JSONObject(responseBody.string()); + return jsonObject.getString("message"); + } catch (Exception e) { + return e.getMessage(); + } + } +}