Merge branch 'developToMapPravilnie' of s416084/find-my-tutor-android into develop

This commit is contained in:
Mieszko Wrzeszczyński 2018-11-06 09:35:38 +00:00 committed by Gogs
commit c62b901c10
13 changed files with 215 additions and 107 deletions

View File

@ -34,6 +34,8 @@ import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static com.uam.wmi.findmytutor.utils.PrefUtils.storeBackgroundLocationStatus;
public abstract class BaseActivity
extends AppCompatActivity
@ -57,8 +59,6 @@ public abstract class BaseActivity
private ActionBarDrawerToggle actionBarDrawerToggle;
private SharingFragment sharingFragment;
boolean boolean_permission;
private Fragment userListFragment;
private ActiveFragment activeFragment = ActiveFragment.NONE;
@ -87,9 +87,13 @@ public abstract class BaseActivity
startActivity(launchIntent);
} else if (itemName.equals(getResources().getString(R.string.navigation_item_logout))) {
stopBackgroundLocalizationTask();
if(PrefUtils.isBackgroundLocationServiceRunning(getApplicationContext())) {
stopBackgroundLocalizationTask();
}
storeBackgroundLocationStatus(getApplication(),false);
PrefUtils.storeIsLoggedIn(getApplicationContext(),false);
PrefUtils.cleanUserLocalStorage(getApplicationContext());
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(getBaseContext().getPackageName());
if (i != null) {
@ -111,12 +115,12 @@ public abstract class BaseActivity
sharingFragment = new SharingFragment();
userListFragment = new UsersListFragment();
isTutor = PrefUtils.getIsTutor(getApplicationContext());
if (!isTutor) {
navigationView.findViewById(R.id.nav_profile).setVisibility(View.GONE);
}
checkPermissions();
}
@ -168,32 +172,24 @@ public abstract class BaseActivity
}
public void startBackgroundLocalizationTask() {
if ((ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)) {
checkPermissions();
if ((ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION))) {
Intent startIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
} else {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION
},
REQUEST_PERMISSIONS);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(startIntent);
} else {
Intent startIntent = new Intent(getApplicationContext(), BackgroundLocalizationService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(startIntent);
} else {
startService(startIntent);
}
startService(startIntent);
}
}
public void handleBackgroundTaskLifeCycle(boolean isLocationEnabled) {
if (isLocationEnabled) {
public void handleBackgroundTaskLifeCycle() {
if (PrefUtils.isEnableSharingLocalization(getApplicationContext())
&& !PrefUtils.isBackgroundLocationServiceRunning(getApplicationContext())) {
startBackgroundLocalizationTask();
} else {
} else if(PrefUtils.isBackgroundLocationServiceRunning(getApplicationContext())) {
stopBackgroundLocalizationTask();
}
}

View File

@ -176,7 +176,7 @@ public class LoginActivity extends AppCompatActivity {
private void getUserProfile(String userId) {
disposable.add(userService.getUserByID(userId)
disposable.add(userService.getUserById(userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::saveUserProfileToSharedPreferences, this::handleError));

View File

@ -1,63 +1,72 @@
package com.uam.wmi.findmytutor.activity;
import android.Manifest;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.annimon.stream.Stream;
import com.auth0.android.jwt.Claim;
import com.auth0.android.jwt.JWT;
import com.jakewharton.retrofit2.adapter.rxjava2.HttpException;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Icon;
import com.mapbox.mapboxsdk.annotations.IconFactory;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraPosition;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.location.LocationComponent;
import com.mapbox.mapboxsdk.location.LocationComponentOptions;
import com.mapbox.mapboxsdk.location.modes.CameraMode;
import com.mapbox.mapboxsdk.location.modes.RenderMode;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.sources.VectorSource;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import android.graphics.Color;
import android.view.View;
import android.view.animation.LinearInterpolator;
import android.widget.Button;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.style.layers.CircleLayer;
import com.mapbox.mapboxsdk.style.layers.Layer;
import com.mapbox.mapboxsdk.style.sources.VectorSource;
import com.uam.wmi.findmytutor.R;
import com.uam.wmi.findmytutor.model.Coordinate;
import com.uam.wmi.findmytutor.model.DutyHourViewModel;
import com.uam.wmi.findmytutor.model.JwtToken;
import com.uam.wmi.findmytutor.model.TutorTabViewModel;
import com.uam.wmi.findmytutor.model.User;
import com.uam.wmi.findmytutor.network.ApiClient;
import com.uam.wmi.findmytutor.service.CoordinateService;
import com.uam.wmi.findmytutor.service.UserService;
import com.uam.wmi.findmytutor.utils.PrefUtils;
import com.uam.wmi.findmytutor.utils.RestApiHelper;
import com.uam.wmi.findmytutor.utils.mapUtils;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
@ -65,50 +74,52 @@ import io.reactivex.observers.DisposableSingleObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import timber.log.Timber;
import java.util.Locale;
import static com.mapbox.mapboxsdk.style.layers.Property.NONE;
import static com.mapbox.mapboxsdk.style.layers.Property.VISIBLE;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius;
import static com.mapbox.mapboxsdk.style.layers.PropertyFactory.visibility;
import static com.uam.wmi.findmytutor.R.id.activity_content;
public class MapActivity extends BaseActivity
implements PermissionsListener, OnMapReadyCallback {
private String tag = getClass().getName();
String currentLanguage = "pl", currentLang;
private String tag = getClass().getName();
private PermissionsManager permissionsManager;
private LocationComponent locationComponent;
LocationManager mLocationManager;
private CoordinateService coordinateService;
private CompositeDisposable disposable = new CompositeDisposable();
private UserService userService;
private CompositeDisposable disposable = new CompositeDisposable();
private int mInterval = 10000;
private Handler mHandler = new Handler();
private Runnable mStatusChecker;
private MapView mapView;
private MapboxMap mapboxMap;
private Marker droppedMarker;
private HashMap<String, Coordinate> coordsMap = new HashMap<>();
private HashMap<String, Marker> markerHash = new HashMap<>();
private int zoomParam = 17;
private int bearingParam = 180;
private int tiltParam = 30;
Locale myLocale;
String currentLanguage = "pl", currentLang;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final SharedPreferences sharedPref = getSharedPreferences("fmtPrefs", Context.MODE_PRIVATE);
final String authToken = sharedPref.getString("authToken", null);
// fetching coords service
coordinateService = ApiClient.getClient(getApplicationContext())
.create(CoordinateService.class);
//
userService = ApiClient.getClient(getApplicationContext())
.create(UserService.class);
mStatusChecker = () -> {
try {
fetchTopCoords();
@ -125,7 +136,7 @@ public class MapActivity extends BaseActivity
mapView.getMapAsync(this);
//start background task
startBackgroundLocalizationTask();
handleBackgroundTaskLifeCycle();
currentLanguage = getIntent().getStringExtra(currentLang);
}
@ -134,22 +145,71 @@ public class MapActivity extends BaseActivity
@Override
public void onMapReady(MapboxMap mapboxMap) {
MapActivity.this.mapboxMap = mapboxMap;
mStatusChecker.run();
enableLocationPlugin();
// // TODO what should happend on click?
// mapboxMap.setOnMarkerClickListener(marker1 -> {
//
// // Show a toast with the title of the selected marker
//// Toast.makeText(MapActivity.this, marker.getTitle(), Toast.LENGTH_SHORT).show();
// return true;
// });
mapboxMap.setOnMarkerClickListener(marker -> {
createMarkerModal(marker.getTitle());
return true;
});
setOnMapLongClickListener();
// addStaticLayer();
}
private void createMarkerModal(String userId) {
disposable.add(userService.getUserById(userId)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(this::createMarkerModal, this::handleError));
}
private void createMarkerModal(User user) {
String cordStatus = coordsMap.get(user.getId()).getLabel();
LayoutInflater layoutInflaterAndroid = LayoutInflater.from(getApplicationContext());
@SuppressLint("InflateParams") View view = layoutInflaterAndroid.inflate(R.layout.marker_modal, null);
AlertDialog.Builder alertDialogBuilderUserInput = new android.support.v7.app.AlertDialog.Builder(this);
alertDialogBuilderUserInput.setView(view);
alertDialogBuilderUserInput.setNegativeButton(R.string.cancel, (dialog, id) -> {
// User cancelled the dialog
});
TextView userName = view.findViewById(R.id.userName);
TextView status = view.findViewById(R.id.label);
userName.setText(String.format("%s %s", user.getFirstName(), user.getLastName()));
status.setText(String.format("%s ", cordStatus));
final AlertDialog alertDialog = alertDialogBuilderUserInput.create();
alertDialog.show();
}
private void handleError(Throwable error) {
showError(error);
}
private void showError(Throwable e) {
String message;
if (e instanceof HttpException) {
ResponseBody responseBody = ((HttpException) e).response().errorBody();
message = RestApiHelper.getErrorMessage(responseBody);
}else {
message = "Network Error!";
}
Toast.makeText(MapActivity.this, message, Toast.LENGTH_SHORT).show();
}
private void setOnMapLongClickListener() {
final boolean[] cancel = {false};
@ -299,11 +359,11 @@ public class MapActivity extends BaseActivity
@Override
public void onSuccess(List<Coordinate> coordsList) {
Log.e(tag, "");
for (Coordinate element : coordsList) {
String id = element.getUserId();
String newLabel = element.getLabel();
Coordinate coordinate = coordsMap.get(id);
Log.e(tag, "hashMapSize: " + coordsMap.size());
@ -320,6 +380,7 @@ public class MapActivity extends BaseActivity
if (!statement) {
Log.e(tag, "replace and animate");
Marker marker = markerHash.get(id);
LatLng toDestination = new LatLng(element.getLatitude(), element.getLongitude());
// TODO fix flickiering markers
ValueAnimator markerAnimator = ObjectAnimator.ofObject(marker, "position",
@ -330,26 +391,28 @@ public class MapActivity extends BaseActivity
markerAnimator.setInterpolator(new LinearInterpolator());
markerAnimator.start();
// chba niepotrzbene
mapboxMap.getMarkerViewManager().update();
coordsMap.put(id, element);
marker.setPosition(toDestination);
}
} else {
Log.e(tag, "Marker Added: " + id);
coordsMap.put(id, element);
Marker marker = mapboxMap.addMarker(new MarkerOptions()
.title(element.getLabel())
.title(id)
.position(new LatLng(element.getLatitude(), element.getLongitude())));
markerHash.put(id, marker);
}
coordsMap.get(id).setLabel(newLabel);
}
for (Coordinate coordinate : coordsMap.values()) {
/* for (Coordinate coordinate : coordsMap.values()) {
// 300000 = 5mins
if ((System.currentTimeMillis() - coordinate.getTimeStamp()) > (long) 300000) {
String id = coordinate.getUserId();
@ -359,7 +422,7 @@ public class MapActivity extends BaseActivity
mapboxMap.removeMarker(markerToRemove);
}
}
}*/
}
@ -438,8 +501,14 @@ public class MapActivity extends BaseActivity
@SuppressWarnings({"MissingPermission"})
private void enableLocationPlugin() {
Log.e(tag, "enableLocationPlugin");
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
Log.e(tag, "enableLocationPlugin true");
FloatingActionButton myLocationButton = findViewById(R.id.myLocationButton);
myLocationButton.setVisibility(View.VISIBLE);
LocationComponentOptions options = LocationComponentOptions.builder(this)
.trackingGesturesManagement(true)
@ -460,7 +529,6 @@ public class MapActivity extends BaseActivity
locationComponent.setCameraMode(CameraMode.TRACKING);
locationComponent.setRenderMode(RenderMode.COMPASS);
// Button 4 centring
FloatingActionButton myLocFAB = findViewById(R.id.myLocationButton);
myLocFAB.setOnClickListener(v -> {
@ -485,8 +553,12 @@ public class MapActivity extends BaseActivity
tiltParam = (tiltParam == 30) ? 0 : 30;
});
} else {
Log.e(tag, "enableLocationPlugin false");
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
permissionsManager.onRequestPermissionsResult(0, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, new int[]{0});
}
}
@ -503,11 +575,11 @@ public class MapActivity extends BaseActivity
@Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
finish();
}
// if (granted) {
// enableLocationPlugin();
// } else {
// Toast.makeText(this, R.string.user_location_permission_not_granted, Toast.LENGTH_LONG).show();
// finish();
// }
}
}

View File

@ -44,11 +44,6 @@ public class SharingFragment extends PreferenceFragment {
locationLevelMapping.put(1,"approximated");
locationLevelMapping.put(2,"exact");
/* statusMapping = new HashMap<Integer, String>();
statusMapping.put(0,"presence");
statusMapping.put(1,"approximated");
statusMapping.put(2,"exact");*/
addPreferencesFromResource(R.layout.pref_sharing);
Preference manualStatus = findPreference("key_manual_status");
Preference locationSharing = findPreference("key_sharing_enabled");
@ -74,9 +69,8 @@ public class SharingFragment extends PreferenceFragment {
});
locationSharing.setOnPreferenceChangeListener((buttonView, newValue) -> {
// PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) isChecked);
// Toast.makeText(getApplicationContext(), Boolean.toString(PrefUtils.isEnableSharingLocalization(getApplicationContext())), Toast.LENGTH_LONG).show();
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle((Boolean) newValue);
PrefUtils.storeEnableSharingLocalization(getApplicationContext(), (Boolean) newValue);
((MapActivity)getActivity()).handleBackgroundTaskLifeCycle();
return true;
});
}

View File

@ -10,7 +10,6 @@ import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.os.AsyncTask;
@ -40,6 +39,8 @@ import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import timber.log.Timber;
import static com.uam.wmi.findmytutor.utils.PrefUtils.storeBackgroundLocationStatus;
public class BackgroundLocalizationService extends Service {
private static final String TAG = "MyLocationService";
@ -48,6 +49,7 @@ public class BackgroundLocalizationService extends Service {
public static String str_receiver = "background.location.broadcast";
private static long notify_interval = 10000;
Location mLastLocation;
Boolean stopService = false;
ArrayList<String> providers = new ArrayList<String>();
LocationListener[] mLocationListeners;
@ -79,13 +81,11 @@ public class BackgroundLocalizationService extends Service {
Log.e(TAG, "onStartCommand");
super.onStartCommand(intent, flags, startId);
//call startForeground first
boolean stopService = false;
if (intent != null) {
stopService = intent.getBooleanExtra("request_stop", false);
}
if (stopService) {
storeBackgroundLocationStatus(getApplication(),false);
stopForeground(true);
stopSelf();
return START_STICKY;
@ -97,7 +97,7 @@ public class BackgroundLocalizationService extends Service {
@Override
public void onCreate() {
Log.e(TAG, "onCreate");
storeBackgroundLocationStatus(getApplication(),true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
startMyOwnForeground();
@ -129,15 +129,18 @@ public class BackgroundLocalizationService extends Service {
providerIndex++;
}
mStatusChecker = () -> {
try {
fn_getlocation();
} finally {
mHandler.postDelayed(mStatusChecker, notify_interval);
}
};
if(!stopService){
mStatusChecker = () -> {
try {
fn_getlocation();
} finally {
mHandler.postDelayed(mStatusChecker, notify_interval);
}
};
AsyncTask.execute(mStatusChecker);
}
AsyncTask.execute(mStatusChecker);
}
@RequiresApi(api = Build.VERSION_CODES.O)
@ -206,7 +209,6 @@ public class BackgroundLocalizationService extends Service {
super.onDestroy();
mHandler.removeCallbacks(mStatusChecker);
if (mLocationManager != null) {
for (LocationListener listener : mLocationListeners) {
try {
@ -283,10 +285,9 @@ public class BackgroundLocalizationService extends Service {
latitude,
longitude,
altitude,
PrefUtils.getUserFirstName(getApplicationContext()) + " " + PrefUtils.getUserLastName(getApplicationContext()) + " " + PrefUtils.getUserStatus(getApplicationContext()),
PrefUtils.getUserStatus(getApplicationContext()),
PrefUtils.getUserId(getApplicationContext()),
PrefUtils.getLocationLevel(getApplicationContext())
);
disposable.add(

View File

@ -40,7 +40,7 @@ public interface UserService {
Single<PagedResultReturnedTutors> getPagedStudents(@Path("pageNum") String pageNum);
@GET("api/users/{id}")
Single<User> getUserByID(@Path("id") String userID);
Single <User> getUserById(@Path("id") String userID);
@PUT("api/users/{id}")
Completable updateUserByID(@Path("id") String userID, @Body User user);

View File

@ -35,6 +35,9 @@ public class PrefUtils {
editor.clear().apply();
}
public static void storeApiKey(Context context, String apiKey) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putString("API_KEY", apiKey);
@ -55,7 +58,6 @@ public class PrefUtils {
return getSharedPreferences(context).getString("USER_ID", null);
}
public static String getUserStatus(Context context) {
return getSharedPreferences(context).getString("status_entry", "Available");
}
@ -139,5 +141,14 @@ public class PrefUtils {
return getSharedPreferences(context).getString("LOCALE", "pl");
}
public static Boolean isBackgroundLocationServiceRunning(Context context) {
return getSharedPreferences(context).getBoolean("BACKGROUND_SERVICE_STATUS", false);
}
public static void storeBackgroundLocationStatus(Context context, Boolean status) {
SharedPreferences.Editor editor = getSharedPreferences(context).edit();
editor.putBoolean("BACKGROUND_SERVICE_STATUS", status);
editor.apply();
}
}

View File

@ -25,6 +25,7 @@ public class RestApiHelper extends Activity {
} catch (Exception e) {
return e.getMessage();
}
}
@ -34,6 +35,8 @@ public class RestApiHelper extends Activity {
if (e instanceof HttpException) {
ResponseBody responseBody = ((HttpException) e).response().errorBody();
message = RestApiHelper.getErrorMessage(responseBody);
} else {
message ="Network Error !";
}
Snackbar snackbar = Snackbar.make(findViewById(R.id.activity_content), message, Snackbar.LENGTH_LONG);

Binary file not shown.

After

Width:  |  Height:  |  Size: 923 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 923 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 923 B

View File

@ -52,6 +52,7 @@
android:background="@color/half_black"
android:backgroundTint="@color/materialDarkGrey"
android:src="@android:drawable/ic_menu_mylocation"
android:visibility="invisible"
app:borderWidth="0dp"
app:elevation="6dp"
app:fabSize="normal"

View File

@ -0,0 +1,30 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_margin"
android:paddingTop="@dimen/activity_margin"
android:paddingRight="@dimen/activity_margin">
<TextView
android:id="@+id/userName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="@dimen/dimen_10"
android:fontFamily="sans-serif-medium"
android:lineSpacingExtra="8sp"
android:textColor="@color/colorAccent"
android:textSize="@dimen/lbl_new_note_title"
android:textStyle="normal" />
<TextView
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:lineSpacingExtra="8sp"
android:paddingTop="5dp"
android:textColor="@color/note_list_text"
/>
</LinearLayout>