Merge branch 'sharing-tab-rest' of s416084/find-my-tutor-android into develop

This commit is contained in:
Mieszko Wrzeszczyński 2018-10-14 11:56:22 +00:00 committed by Gogs
commit bd775d5d0d
8 changed files with 220 additions and 306 deletions

View File

@ -8,7 +8,7 @@ android {
} }
defaultConfig { defaultConfig {
applicationId "com.uam.wmi.findmytutor" applicationId "com.uam.wmi.findmytutor"
minSdkVersion 23 minSdkVersion 22
targetSdkVersion 27 targetSdkVersion 27
versionCode 1 versionCode 1
versionName "1.0" versionName "1.0"

View File

@ -33,12 +33,16 @@ import android.widget.ToggleButton;
import com.auth0.android.jwt.Claim; import com.auth0.android.jwt.Claim;
import com.auth0.android.jwt.JWT; import com.auth0.android.jwt.JWT;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.uam.wmi.findmytutor.R; import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.model.JwtToken; import com.uam.wmi.findmytutor.model.JwtToken;
import com.uam.wmi.findmytutor.model.LdapUser; 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.network.ApiClient;
import com.uam.wmi.findmytutor.service.LdapService; 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.PrefUtils;
import com.uam.wmi.findmytutor.utils.RestApiHelper;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -47,6 +51,7 @@ import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.observers.DisposableSingleObserver; import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers; import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import static android.Manifest.permission.READ_CONTACTS; import static android.Manifest.permission.READ_CONTACTS;
@ -326,6 +331,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
private final String mPassword; private final String mPassword;
private boolean isTutor; private boolean isTutor;
private LdapService ldapService; private LdapService ldapService;
private UserService userService;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private Boolean isAuthorizate; private Boolean isAuthorizate;
@ -334,16 +340,52 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
mEmail = email; mEmail = email;
mPassword = password; mPassword = password;
isTutor = loginOption; isTutor = loginOption;
this.ldapService = ApiClient.getClient(getApplicationContext()) isAuthorizate = false;
ldapService = ApiClient.getClient(getApplicationContext())
.create(LdapService.class); .create(LdapService.class);
this.isAuthorizate = false; userService = ApiClient.getClient(getApplicationContext())
.create(UserService.class);
PrefUtils.storeIsTutor(getApplicationContext(), this.isTutor); 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<User>() {
@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 @Override
protected Boolean doInBackground(Void... params) { 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( disposable.add(
ldapService ldapService
@ -362,7 +404,7 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
PrefUtils.storeApiKey(getApplicationContext(), token); PrefUtils.storeApiKey(getApplicationContext(), token);
PrefUtils.storeUserId(getApplicationContext(), role.asString()); PrefUtils.storeUserId(getApplicationContext(), role.asString());
onPostExecute(true); getUserProfile(role.asString());
} }
@Override @Override
@ -370,8 +412,8 @@ public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<
Log.e("LoginError", "onError: " + e.getMessage()); Log.e("LoginError", "onError: " + e.getMessage());
} }
})); }));
return true;
return true;
} }
@Override @Override

View File

@ -3,15 +3,11 @@ package com.uam.wmi.findmytutor.activity;
import android.app.Fragment; import android.app.Fragment;
import android.app.FragmentTransaction; import android.app.FragmentTransaction;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences;
import android.location.Geocoder;
import android.content.res.Configuration; import android.content.res.Configuration;
import android.os.Bundle; import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomNavigationView; import android.support.design.widget.BottomNavigationView;
import android.support.design.widget.FloatingActionButton; import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.ActivityCompat; import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat; import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity; import android.support.v7.app.AppCompatActivity;
@ -27,22 +23,22 @@ import android.content.pm.PackageManager;
import android.os.Build; import android.os.Build;
import android.view.View; import android.view.View;
import android.widget.AdapterView;
import android.widget.FrameLayout; import android.widget.FrameLayout;
import android.support.v7.widget.Toolbar;
import android.widget.ListView; import android.widget.ListView;
import android.widget.Toast; import android.widget.Toast;
import android.support.v7.widget.Toolbar;
import com.mapbox.mapboxsdk.Mapbox; import com.mapbox.mapboxsdk.Mapbox;
import com.uam.wmi.findmytutor.ListViewAdapter; import com.uam.wmi.findmytutor.ListViewAdapter;
import com.uam.wmi.findmytutor.R; 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.service.BackgroundLocalizationService;
import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.PrefUtils;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity { public class MainActivity extends AppCompatActivity {
private BottomNavigationView mMainNav; private BottomNavigationView mMainNav;
@ -54,10 +50,6 @@ public class MainActivity extends AppCompatActivity {
private static final int REQUEST_PERMISSIONS = 100; private static final int REQUEST_PERMISSIONS = 100;
boolean boolean_permission; boolean boolean_permission;
SharedPreferences mPref;
SharedPreferences.Editor medit;
Double latitude, longitude;
Geocoder geocoder;
private DrawerLayout drawerLayout; private DrawerLayout drawerLayout;
private ActionBarDrawerToggle actionBarDrawerToggle; private ActionBarDrawerToggle actionBarDrawerToggle;
@ -79,10 +71,11 @@ public class MainActivity extends AppCompatActivity {
configureconfigureNavigationDrawer(); configureconfigureNavigationDrawer();
configureBottomNavigationView(); configureBottomNavigationView();
configureLogoutButton(); configureLogoutButton();
} }
private void configureconfigureNavigationDrawer() { private void configureconfigureNavigationDrawer() {
listView = (ListView) findViewById(R.id.list_item); listView = findViewById(R.id.list_item);
Toolbar toolbar = findViewById(R.id.toolbar_main); Toolbar toolbar = findViewById(R.id.toolbar_main);
setSupportActionBar(toolbar); setSupportActionBar(toolbar);
@ -90,13 +83,7 @@ public class MainActivity extends AppCompatActivity {
adapter = new ListViewAdapter(this, R.layout.item_listview, stringArrayList); adapter = new ListViewAdapter(this, R.layout.item_listview, stringArrayList);
listView.setAdapter(adapter); listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { listView.setOnItemClickListener((parent, view, position, id) -> Toast.makeText(MainActivity.this, (String)parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show());
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, (String)parent.getItemAtPosition(position), Toast.LENGTH_SHORT).show();
}
});
drawerLayout = findViewById(R.id.drawer_layout); drawerLayout = findViewById(R.id.drawer_layout);
@ -121,8 +108,8 @@ public class MainActivity extends AppCompatActivity {
private void configureBottomNavigationView(){ private void configureBottomNavigationView(){
mMainFrame = (FrameLayout) findViewById(R.id.main_frame); mMainFrame = findViewById(R.id.main_frame);
mMainNav = (BottomNavigationView) findViewById(R.id.main_nav); mMainNav = findViewById(R.id.main_nav);
isTutor = PrefUtils.getIsTutor(getApplicationContext()); isTutor = PrefUtils.getIsTutor(getApplicationContext());
if (!isTutor) { if (!isTutor) {
@ -138,23 +125,20 @@ public class MainActivity extends AppCompatActivity {
mMainNav.setSelectedItemId(R.id.nav_map); mMainNav.setSelectedItemId(R.id.nav_map);
/* code below is resposible for changing colours of tabs in main tab menu */ /* code below is resposible for changing colours of tabs in main tab menu */
mMainNav.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() { mMainNav.setOnNavigationItemSelectedListener(item -> {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem item) {
switch (item.getItemId()) { switch (item.getItemId()) {
case R.id.nav_map: case R.id.nav_map:
setFragment(mapFragment); setFragment(mapFragment);
return true; return true;
case R.id.nav_notif: case R.id.nav_notif:
setFragment(notificationFragment); setFragment(notificationFragment);
return true; return true;
case R.id.nav_profile: case R.id.nav_profile:
setFragment(profileFragment); setFragment(profileFragment);
return true; return true;
default: default:
return false; return false;
}
} }
}); });
} }
@ -163,19 +147,16 @@ public class MainActivity extends AppCompatActivity {
// Logout button // Logout button
final FloatingActionButton button = findViewById(R.id.logoutButton); final FloatingActionButton button = findViewById(R.id.logoutButton);
button.setOnClickListener(new View.OnClickListener() { button.setOnClickListener(view -> {
@Override PrefUtils.cleanUserLocalStorage(getApplicationContext());
public void onClick(View view) {
PrefUtils.cleanUserLocalStorage(getApplicationContext());
Intent i = getBaseContext().getPackageManager() Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName()); .getLaunchIntentForPackage(getBaseContext().getPackageName());
if (i != null) { if (i != null) {
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
startActivity(i);
finish();
} }
startActivity(i);
finish();
}); });
} }
@ -230,8 +211,6 @@ public class MainActivity extends AppCompatActivity {
protected void onPostCreate(Bundle savedInstanceState) { protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState); super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState(); actionBarDrawerToggle.syncState();
if (isTutor) { if (isTutor) {

View File

@ -44,14 +44,15 @@ public class Coordinate extends BaseResponse {
@SerializedName("label") @SerializedName("label")
private String 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 (!latitudeRange.contains(latitude)) throw new IllegalArgumentException("Inappropriate latitude value" + latitude);
//if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude); //if (!longtitudeRange.contains(longitude)) throw new IllegalArgumentException("Inappropriate longitude value" + longitude);
this.latitude = latitude; this.latitude = latitude;
this.longitude = longitude; this.longitude = longitude;
this.userId = userId; this.altitude = altitude;
this.label = label; this.label = label;
this.userId = userId;
} }
public Coordinate (Double latitude) { public Coordinate (Double latitude) {

View File

@ -26,11 +26,16 @@ import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.uam.wmi.findmytutor.model.Coordinate; import com.uam.wmi.findmytutor.model.Coordinate;
import com.uam.wmi.findmytutor.network.ApiClient; import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.utils.PrefUtils; import com.uam.wmi.findmytutor.utils.PrefUtils;
import com.uam.wmi.findmytutor.utils.RestApiHelper;
import org.json.JSONObject; import org.json.JSONObject;
import java.io.IOException; import java.io.IOException;
import java.io.InterruptedIOException;
import java.lang.reflect.Array;
import java.net.SocketTimeoutException; import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer; import java.util.Timer;
import java.util.TimerTask; import java.util.TimerTask;
@ -48,18 +53,14 @@ public class BackgroundLocalizationService extends Service {
private LocationManager mLocationManager = null; private LocationManager mLocationManager = null;
private static final int LOCATION_INTERVAL = 1000; private static final int LOCATION_INTERVAL = 1000;
private static final float LOCATION_DISTANCE = 10f; private static final float LOCATION_DISTANCE = 10f;
private Handler mHandler = new Handler();
private static long notify_interval = 10000; private static long notify_interval = 10000;
private Handler mHandler = new Handler();
double latitude, longitude;
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
Location mLastLocation; Location mLastLocation;
Intent intent; Intent intent;
LocationManager locationManager;
Location location;
ArrayList<String> providers = new ArrayList<String>();
LocationListener[] mLocationListeners ;
private class LocationListener implements android.location.LocationListener { 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 @Override
public IBinder onBind(Intent arg0) { public IBinder onBind(Intent arg0) {
return null; return null;
@ -110,9 +105,20 @@ public class BackgroundLocalizationService extends Service {
return START_STICKY; 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 @Override
public void onCreate() { public void onCreate() {
Log.e(TAG, "onCreate"); Log.e(TAG, "onCreate");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) 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") Notification notification = new NotificationCompat.Builder(this, "NOTIFICATION_CHANNEL")
.setContentText("Content").build(); .setContentText("Content").build();
startForeground(1001, notification); startForeground(1001, notification);
} }
initializeLocationManager(); initializeLocationManager();
try { Integer providerIndex = 0;
mLocationManager.requestLocationUpdates(
LocationManager.PASSIVE_PROVIDER, for (LocationListener listener : mLocationListeners) {
LOCATION_INTERVAL, try {
LOCATION_DISTANCE, mLocationManager.requestLocationUpdates(
mLocationListeners[0] providers.get(providerIndex),
); LOCATION_INTERVAL,
} catch (java.lang.SecurityException ex) { LOCATION_DISTANCE,
Log.i(TAG, "fail to request location update, ignore", ex); listener
} catch (IllegalArgumentException ex) { );
Log.d(TAG, "network provider does not exist, " + ex.getMessage()); } 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(); Timer mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval); mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver); intent = new Intent(str_receiver);
fn_getlocation();
} }
@RequiresApi(api = Build.VERSION_CODES.O) @RequiresApi(api = Build.VERSION_CODES.O)
@ -180,80 +180,35 @@ public class BackgroundLocalizationService extends Service {
private void fn_getlocation() { private void fn_getlocation() {
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); // TODO: Consider calling
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); // ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
if (!isGPSEnable && !isNetworkEnable) { // public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
} else { // to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
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);
}
}
}
} }
} List<String> 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 { private class TimerTaskToGetLocation extends TimerTask {
@Override @Override
@ -263,23 +218,21 @@ public class BackgroundLocalizationService extends Service {
} }
private void fn_update(Location location) { 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(); new Task(location).execute();
} }
@Override @Override
public void onDestroy() { public void onDestroy() {
Log.e(TAG, "onDestroy"); Log.e(TAG, "onDestroy");
super.onDestroy(); super.onDestroy();
if (mLocationManager != null) { if (mLocationManager != null) {
for (int i = 0; i < mLocationListeners.length; i++) { for (LocationListener listener : mLocationListeners) {
try { 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) { 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; return;
} }
mLocationManager.removeUpdates(mLocationListeners[i]); mLocationManager.removeUpdates(listener);
} catch (Exception ex) { } catch (Exception ex) {
Log.i(TAG, "fail to remove location listener, ignore", ex); Log.i(TAG, "fail to remove location listener, ignore", ex);
} }
@ -289,6 +242,7 @@ public class BackgroundLocalizationService extends Service {
private void initializeLocationManager() { private void initializeLocationManager() {
Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE); Log.e(TAG, "initializeLocationManager - LOCATION_INTERVAL: " + LOCATION_INTERVAL + " LOCATION_DISTANCE: " + LOCATION_DISTANCE);
if (mLocationManager == null) { if (mLocationManager == null) {
mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
} }
@ -297,26 +251,27 @@ public class BackgroundLocalizationService extends Service {
private class Task extends AsyncTask { private class Task extends AsyncTask {
private Double latitude; private Double latitude;
private Double longitude; private Double longitude;
private Double altitude;
private CompositeDisposable disposable = new CompositeDisposable(); private CompositeDisposable disposable = new CompositeDisposable();
private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext()) private CoordinateService coordinateService = ApiClient.getClient(getApplicationContext())
.create(CoordinateService.class); .create(CoordinateService.class);
private Task(Location location) { private Task(Location location) {
this.latitude = location.getLatitude(); latitude = location.getLatitude();
this.longitude = location.getLongitude(); longitude = location.getLongitude();
altitude = location.getAltitude();
} }
@Override @Override
protected Object doInBackground(Object[] objects) { protected Object doInBackground(Object[] objects) {
try { try {
Coordinate coordinate = new Coordinate( Coordinate coordinate = new Coordinate(
this.latitude, latitude,
this.longitude, longitude,
PrefUtils.getUserStatus(getApplicationContext()), altitude,
PrefUtils.getUserFirstName(getApplicationContext()) + " " + PrefUtils.getUserLastName(getApplicationContext()),
PrefUtils.getUserId(getApplicationContext()) PrefUtils.getUserId(getApplicationContext())
); );
@ -335,14 +290,14 @@ public class BackgroundLocalizationService extends Service {
@SuppressLint("LongLogTag") @SuppressLint("LongLogTag")
@Override @Override
public void onError(Throwable e) { public void onError(Throwable e) {
((HttpException) e).code();
Log.e("CoordinateService onError", e.getMessage()); Log.e("CoordinateService onError", e.getMessage());
if (e instanceof HttpException) { if (e instanceof HttpException) {
ResponseBody responseBody = ((HttpException)e).response().errorBody(); ResponseBody responseBody = ((HttpException) e).response().errorBody();
Log.e("CoordinateService onError", getErrorMessage(responseBody)); Log.e("CoordinateService onError", RestApiHelper.getErrorMessage(responseBody));
}
}
} }
})); }));
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
@ -352,14 +307,6 @@ public class BackgroundLocalizationService extends Service {
return null; return null;
} }
private String getErrorMessage(ResponseBody responseBody) {
try {
JSONObject jsonObject = new JSONObject(responseBody.string());
return jsonObject.getString("message");
} catch (Exception e) {
return e.getMessage();
}
}
} }
} }

View File

@ -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<Coordinate>() {
@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;
}
}
}

View File

@ -16,6 +16,12 @@ public class PrefUtils {
return context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE); 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) { public static void storeApiKey(Context context, String apiKey) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit(); SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString("API_KEY", apiKey); editor.putString("API_KEY", apiKey);
@ -61,13 +67,7 @@ public class PrefUtils {
return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false); return getSharedPreferences(context).getBoolean("IS_LOGGED_IN", false);
} }
public static void cleanUserLocalStorage(Context context) { public static void storeIsServiceRunning(Context context, Boolean flag) {
SharedPreferences preferences = getSharedPreferences(context);
SharedPreferences.Editor editor = preferences.edit();
editor.clear().apply();
}
public static void storeIsServiceRunning(Context context, Boolean flag) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit(); SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putBoolean("IS_SERVIS_RUNNING", flag); editor.putBoolean("IS_SERVIS_RUNNING", flag);
editor.apply(); editor.apply();
@ -77,5 +77,34 @@ public class PrefUtils {
return getSharedPreferences(context).getBoolean("IS_SERVIS_RUNNING", false); 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);
}
} }

View File

@ -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();
}
}
}