610 lines
21 KiB
Java
610 lines
21 KiB
Java
package com.iamthefij.otbeta;
|
|
|
|
import android.Manifest;
|
|
import android.animation.Animator;
|
|
import android.animation.AnimatorListenerAdapter;
|
|
import android.annotation.TargetApi;
|
|
import android.content.Intent;
|
|
import android.content.pm.PackageManager;
|
|
import android.graphics.Color;
|
|
import android.location.LocationListener;
|
|
import android.location.LocationManager;
|
|
import android.support.annotation.NonNull;
|
|
import android.support.design.widget.Snackbar;
|
|
import android.support.v4.app.ActivityCompat;
|
|
import android.support.v7.app.AppCompatActivity;
|
|
import android.app.LoaderManager.LoaderCallbacks;
|
|
|
|
import android.content.CursorLoader;
|
|
import android.content.Loader;
|
|
import android.database.Cursor;
|
|
import android.net.Uri;
|
|
import android.os.AsyncTask;
|
|
|
|
import android.os.Build;
|
|
import android.os.Bundle;
|
|
import android.provider.ContactsContract;
|
|
import android.text.TextUtils;
|
|
import android.util.Log;
|
|
import android.util.SparseArray;
|
|
import android.view.KeyEvent;
|
|
import android.view.View;
|
|
import android.view.View.OnClickListener;
|
|
import android.view.ViewGroup;
|
|
import android.view.inputmethod.EditorInfo;
|
|
import android.widget.ArrayAdapter;
|
|
import android.widget.AutoCompleteTextView;
|
|
import android.widget.BaseAdapter;
|
|
import android.widget.Button;
|
|
import android.widget.EditText;
|
|
import android.widget.Spinner;
|
|
import android.widget.SpinnerAdapter;
|
|
import android.widget.TextView;
|
|
|
|
import com.iamthefij.otbeta.api.Client;
|
|
import com.iamthefij.otbeta.api.Exerciser;
|
|
import com.iamthefij.otbeta.api.Location;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.Collections;
|
|
import java.util.Comparator;
|
|
import java.util.List;
|
|
|
|
import static android.Manifest.permission.READ_CONTACTS;
|
|
import static android.Manifest.permission.ACCESS_FINE_LOCATION;
|
|
|
|
/**
|
|
* A login screen that offers login via email/password.
|
|
*/
|
|
public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor> {
|
|
|
|
/**
|
|
* Ids to identity permission requests.
|
|
*/
|
|
private static final int REQUEST_READ_CONTACTS = 0;
|
|
private static final int REQUEST_ACCESS_FINE_LOCATION = 1;
|
|
|
|
/**
|
|
* Keep track of the login task to ensure we can cancel it if requested.
|
|
*/
|
|
private UserLoginTask mAuthTask = null;
|
|
|
|
// UI references.
|
|
private Spinner mLocationView;
|
|
private AutoCompleteTextView mEmailView;
|
|
private EditText mPasswordView;
|
|
private View mProgressView;
|
|
private View mLoginFormView;
|
|
private Client mClient;
|
|
private Exerciser mExerciser;
|
|
|
|
@Override
|
|
protected void onCreate(Bundle savedInstanceState) {
|
|
super.onCreate(savedInstanceState);
|
|
setContentView(R.layout.activity_login);
|
|
|
|
// Initialize client
|
|
mClient = new Client(this);
|
|
|
|
// Set up the login form.
|
|
mLocationView = (Spinner) findViewById(R.id.location);
|
|
populateLocationList();
|
|
|
|
mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
|
|
populateAutoComplete();
|
|
|
|
mPasswordView = (EditText) findViewById(R.id.password);
|
|
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
|
|
@Override
|
|
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
|
|
if (id == R.id.login || id == EditorInfo.IME_NULL) {
|
|
attemptLogin();
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
});
|
|
|
|
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
|
|
mEmailSignInButton.setOnClickListener(new OnClickListener() {
|
|
@Override
|
|
public void onClick(View view) {
|
|
attemptLogin();
|
|
}
|
|
});
|
|
|
|
mLoginFormView = findViewById(R.id.login_form);
|
|
mProgressView = findViewById(R.id.login_progress);
|
|
}
|
|
|
|
private void populateAutoComplete() {
|
|
if (!mayRequestContacts()) {
|
|
return;
|
|
}
|
|
|
|
getLoaderManager().initLoader(0, null, this);
|
|
}
|
|
|
|
private void populateLocationList() {
|
|
LocationListFetcher locationListFetcher = new LocationListFetcher();
|
|
locationListFetcher.execute();
|
|
}
|
|
|
|
private void sortLocationList() {
|
|
if (!mayRequestLocation()) {
|
|
return;
|
|
}
|
|
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
|
|
return;
|
|
}
|
|
final LocationSpinnerAdapter locationSpinnerAdapter = (LocationSpinnerAdapter) mLocationView.getAdapter();
|
|
if (locationSpinnerAdapter != null && !locationSpinnerAdapter.isEmpty() && !locationSpinnerAdapter.isSorted()) {
|
|
final LocationManager locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
|
|
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, new BasicLocationListener(locationSpinnerAdapter, locationManager));
|
|
android.location.Location currentLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
|
|
if (currentLocation != null) {
|
|
locationSpinnerAdapter.sortByDistance(currentLocation.getLatitude(), currentLocation.getLongitude());
|
|
}
|
|
}
|
|
}
|
|
|
|
private boolean mayRequestContacts() {
|
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
|
return true;
|
|
}
|
|
if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
|
|
return true;
|
|
}
|
|
if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
|
|
Snackbar.make(mEmailView, R.string.contact_permission_rationale, Snackbar.LENGTH_INDEFINITE)
|
|
.setAction(android.R.string.ok, new View.OnClickListener() {
|
|
@Override
|
|
@TargetApi(Build.VERSION_CODES.M)
|
|
public void onClick(View v) {
|
|
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
|
|
}
|
|
});
|
|
} else {
|
|
requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private boolean mayRequestLocation() {
|
|
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
|
|
return true;
|
|
}
|
|
if (checkSelfPermission(ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
|
|
return true;
|
|
}
|
|
if (shouldShowRequestPermissionRationale(ACCESS_FINE_LOCATION)) {
|
|
Snackbar.make(mLocationView, R.string.location_permission_rationale, Snackbar.LENGTH_INDEFINITE)
|
|
.setAction(android.R.string.ok, new View.OnClickListener() {
|
|
@Override
|
|
@TargetApi(Build.VERSION_CODES.M)
|
|
public void onClick(View v) {
|
|
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION);
|
|
}
|
|
});
|
|
} else {
|
|
requestPermissions(new String[]{ACCESS_FINE_LOCATION}, REQUEST_ACCESS_FINE_LOCATION);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/**
|
|
* Callback received when a permissions request has been completed.
|
|
*/
|
|
@Override
|
|
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
|
|
@NonNull int[] grantResults) {
|
|
if (requestCode == REQUEST_READ_CONTACTS) {
|
|
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
|
populateAutoComplete();
|
|
}
|
|
} else if (requestCode == REQUEST_ACCESS_FINE_LOCATION) {
|
|
if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
|
|
sortLocationList();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Attempts to sign in or register the account specified by the login form.
|
|
* If there are form errors (invalid email, missing fields, etc.), the
|
|
* errors are presented and no actual login attempt is made.
|
|
*/
|
|
private void attemptLogin() {
|
|
if (mAuthTask != null) {
|
|
return;
|
|
}
|
|
|
|
// Reset errors.
|
|
mEmailView.setError(null);
|
|
mPasswordView.setError(null);
|
|
|
|
// Store values at the time of the login attempt.
|
|
String email = mEmailView.getText().toString();
|
|
String password = mPasswordView.getText().toString();
|
|
Location location = (Location) mLocationView.getSelectedItem();
|
|
|
|
boolean cancel = false;
|
|
View focusView = null;
|
|
|
|
// Check for a valid password, if the user entered one.
|
|
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) {
|
|
mPasswordView.setError(getString(R.string.error_invalid_password));
|
|
focusView = mPasswordView;
|
|
cancel = true;
|
|
}
|
|
|
|
// Check for a valid email address.
|
|
if (TextUtils.isEmpty(email)) {
|
|
mEmailView.setError(getString(R.string.error_field_required));
|
|
focusView = mEmailView;
|
|
cancel = true;
|
|
} else if (!isEmailValid(email)) {
|
|
mEmailView.setError(getString(R.string.error_invalid_email));
|
|
focusView = mEmailView;
|
|
cancel = true;
|
|
}
|
|
|
|
if (cancel) {
|
|
// There was an error; don't attempt login and focus the first
|
|
// form field with an error.
|
|
focusView.requestFocus();
|
|
} else {
|
|
// Show a progress spinner, and kick off a background task to
|
|
// perform the user login attempt.
|
|
showProgress(true);
|
|
mAuthTask = new UserLoginTask(email, password, location);
|
|
mAuthTask.execute((Void) null);
|
|
}
|
|
}
|
|
|
|
private boolean isEmailValid(String email) {
|
|
return email.contains("@");
|
|
}
|
|
|
|
private boolean isPasswordValid(String password) {
|
|
return password.length() > 4;
|
|
}
|
|
|
|
/**
|
|
* Shows the progress UI and hides the login form.
|
|
*/
|
|
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
|
|
private void showProgress(final boolean show) {
|
|
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
|
|
// for very easy animations. If available, use these APIs to fade-in
|
|
// the progress spinner.
|
|
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
|
|
|
|
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
|
mLoginFormView.animate().setDuration(shortAnimTime).alpha(
|
|
show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
|
|
@Override
|
|
public void onAnimationEnd(Animator animation) {
|
|
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
|
|
}
|
|
});
|
|
|
|
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
|
mProgressView.animate().setDuration(shortAnimTime).alpha(
|
|
show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
|
|
@Override
|
|
public void onAnimationEnd(Animator animation) {
|
|
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
|
|
}
|
|
});
|
|
}
|
|
|
|
@Override
|
|
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
|
|
return new CursorLoader(this,
|
|
// Retrieve data rows for the device user's 'profile' contact.
|
|
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
|
|
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
|
|
|
|
// Select only email addresses.
|
|
ContactsContract.Contacts.Data.MIMETYPE +
|
|
" = ?", new String[]{ContactsContract.CommonDataKinds.Email
|
|
.CONTENT_ITEM_TYPE},
|
|
|
|
// Show primary email addresses first. Note that there won't be
|
|
// a primary email address if the user hasn't specified one.
|
|
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
|
|
}
|
|
|
|
@Override
|
|
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
|
|
List<String> emails = new ArrayList<>();
|
|
cursor.moveToFirst();
|
|
while (!cursor.isAfterLast()) {
|
|
emails.add(cursor.getString(ProfileQuery.ADDRESS));
|
|
cursor.moveToNext();
|
|
}
|
|
|
|
addEmailsToAutoComplete(emails);
|
|
}
|
|
|
|
@Override
|
|
public void onLoaderReset(Loader<Cursor> cursorLoader) {
|
|
|
|
}
|
|
|
|
private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
|
|
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
|
|
ArrayAdapter<String> adapter =
|
|
new ArrayAdapter<>(LoginActivity.this,
|
|
android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
|
|
|
|
mEmailView.setAdapter(adapter);
|
|
}
|
|
|
|
private interface ProfileQuery {
|
|
String[] PROJECTION = {
|
|
ContactsContract.CommonDataKinds.Email.ADDRESS,
|
|
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
|
|
};
|
|
|
|
int ADDRESS = 0;
|
|
int IS_PRIMARY = 1;
|
|
}
|
|
|
|
/**
|
|
* Represents an asynchronous login/registration task used to authenticate
|
|
* the user.
|
|
*/
|
|
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
|
|
|
|
private final String mEmail;
|
|
private final String mPassword;
|
|
private final Location mLocation;
|
|
private Exerciser mTempExerciser;
|
|
|
|
UserLoginTask(String email, String password, Location location) {
|
|
mEmail = email;
|
|
mPassword = password;
|
|
mLocation = location;
|
|
}
|
|
|
|
@Override
|
|
protected Boolean doInBackground(Void... params) {
|
|
mTempExerciser = mClient.login(mEmail, mPassword, mLocation);
|
|
|
|
return (mTempExerciser != null);
|
|
}
|
|
|
|
@Override
|
|
protected void onPostExecute(final Boolean success) {
|
|
mAuthTask = null;
|
|
showProgress(false);
|
|
|
|
if (success) {
|
|
mExerciser = this.mTempExerciser;
|
|
launchMainActivity();
|
|
} else {
|
|
mPasswordView.setError(getString(R.string.error_incorrect_password));
|
|
mPasswordView.requestFocus();
|
|
}
|
|
}
|
|
|
|
@Override
|
|
protected void onCancelled() {
|
|
mAuthTask = null;
|
|
showProgress(false);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Launches the main activity after an exerciser is retrieved
|
|
*/
|
|
private void launchMainActivity() {
|
|
if (mExerciser != null) {
|
|
ExerciserStore exerciserStore = new ExerciserStore(this);
|
|
exerciserStore.saveExerciser(mExerciser);
|
|
Intent nextIntent = new Intent(LoginActivity.this, WorkoutListActivity.class);
|
|
startActivity(nextIntent);
|
|
finish();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Represents an asynchronous task to retrieve locations from the api and populate
|
|
* the location spinner
|
|
*/
|
|
private class LocationListFetcher extends AsyncTask<Void, Void, Boolean> {
|
|
|
|
private final android.location.Location mCurrentLocation;
|
|
private List<Location> mLocations;
|
|
|
|
public LocationListFetcher() {
|
|
mCurrentLocation = null;
|
|
mLocations = null;
|
|
}
|
|
|
|
public LocationListFetcher(android.location.Location currentLocation) {
|
|
mCurrentLocation = currentLocation;
|
|
}
|
|
|
|
@Override
|
|
protected Boolean doInBackground(Void... params) {
|
|
mLocations = mClient.getLocationsWithDetail();
|
|
return (mLocations != null);
|
|
}
|
|
|
|
@Override
|
|
protected void onPostExecute(Boolean success) {
|
|
super.onPostExecute(success);
|
|
if (success) {
|
|
LocationSpinnerAdapter locationSpinnerAdapter = new LocationSpinnerAdapter(mLocations);
|
|
mLocationView.setAdapter(locationSpinnerAdapter);
|
|
|
|
if (mCurrentLocation != null) {
|
|
locationSpinnerAdapter.sortByDistance(mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude());
|
|
}
|
|
|
|
sortLocationList();
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Adapter to show locations in spinner
|
|
*/
|
|
private class LocationSpinnerAdapter extends BaseAdapter implements SpinnerAdapter {
|
|
|
|
private final List<Location> mLocations;
|
|
private boolean mSorted;
|
|
|
|
public boolean isSorted() {
|
|
return mSorted;
|
|
}
|
|
|
|
public LocationSpinnerAdapter(List<Location> locations) {
|
|
mLocations = locations;
|
|
mSorted = false;
|
|
}
|
|
|
|
@Override
|
|
public int getCount() {
|
|
return mLocations.size();
|
|
}
|
|
|
|
@Override
|
|
public Object getItem(int position) {
|
|
return mLocations.get(position);
|
|
}
|
|
|
|
@Override
|
|
public long getItemId(int position) {
|
|
return position;
|
|
}
|
|
|
|
@Override
|
|
public View getView(int position, View convertView, ViewGroup parent) {
|
|
TextView text;
|
|
if (convertView != null) {
|
|
text = (TextView) convertView;
|
|
} else {
|
|
text = (TextView) getLayoutInflater().inflate(
|
|
android.R.layout.simple_dropdown_item_1line,
|
|
parent,
|
|
false
|
|
);
|
|
}
|
|
text.setTextColor(Color.BLACK);
|
|
text.setText(mLocations.get(position).getName());
|
|
return text;
|
|
}
|
|
|
|
/**
|
|
* Sorts the locations in the list by distance from a given point
|
|
*
|
|
* @param lat latitude of current location to calculate distance from
|
|
* @param lon longitude of current location to calculate distance from
|
|
*/
|
|
public void sortByDistance(double lat, double lon) {
|
|
Collections.sort(mLocations, new LocationDistanceComparator(lat, lon));
|
|
mSorted = true;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Comparator that allows sorting of locations by distance from a point
|
|
*/
|
|
static class LocationDistanceComparator implements Comparator<Location> {
|
|
|
|
private final double mLat;
|
|
private final double mLon;
|
|
private final SparseArray<Float> mDistances;
|
|
|
|
public LocationDistanceComparator(double lat, double lon) {
|
|
mLat = lat;
|
|
mLon = lon;
|
|
mDistances = new SparseArray<>();
|
|
}
|
|
|
|
private boolean locationHasCoords(Location l) {
|
|
return (l.hasAddress() && l.getAddress().hasLatitude() && l.getAddress().hasLongitude());
|
|
}
|
|
|
|
private float distanceToLocation(Location l) {
|
|
// Try to return from cache
|
|
float distance = mDistances.get(l.getId(), -1f);
|
|
if (distance > 0) {
|
|
return distance;
|
|
}
|
|
|
|
// Calculate the distance between location and provided coordinates
|
|
float[] results = new float[2];
|
|
android.location.Location.distanceBetween(mLat, mLon, l.getAddress().getLatitude(), l.getAddress().getLongitude(), results);
|
|
distance = results[0];
|
|
// Store distance in cache
|
|
mDistances.put(l.getId(), distance);
|
|
|
|
return distance;
|
|
}
|
|
|
|
public int compare(Location l1, Location l2) {
|
|
// TODO: Fix bug here. Getting "Comparison method violates its general contract!"
|
|
if (locationHasCoords(l1) && !locationHasCoords(l2)) {
|
|
return -1;
|
|
} else if (!locationHasCoords(l1) && locationHasCoords(l2)) {
|
|
return 1;
|
|
} else if (locationHasCoords(l1) && locationHasCoords(l2)){
|
|
float distance1 = distanceToLocation(l1);
|
|
float distance2 = distanceToLocation(l2);
|
|
|
|
if (distance1 > distance2) {
|
|
return 1;
|
|
} else if (distance1 < distance2) {
|
|
return -1;
|
|
}
|
|
}
|
|
|
|
// All else equal, let's use name
|
|
if (l1.getName() != null && l2.getName() != null) {
|
|
return l1.getName().compareTo(l2.getName());
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
}
|
|
|
|
private class BasicLocationListener implements LocationListener {
|
|
|
|
private static final String TAG = "LocationListener";
|
|
private final LocationSpinnerAdapter spinnerAdapter;
|
|
private final LocationManager locationManager;
|
|
|
|
public BasicLocationListener(LocationSpinnerAdapter spinnerAdapter, LocationManager locationManager) {
|
|
this.spinnerAdapter = spinnerAdapter;
|
|
this.locationManager = locationManager;
|
|
}
|
|
|
|
@Override
|
|
public void onLocationChanged(android.location.Location location) {
|
|
spinnerAdapter.sortByDistance(location.getLatitude(), location.getLongitude());
|
|
locationManager.removeUpdates(this);
|
|
}
|
|
|
|
@Override
|
|
public void onStatusChanged(String s, int i, Bundle bundle) {
|
|
Log.d(TAG, "onStatusChanged: ");
|
|
}
|
|
|
|
@Override
|
|
public void onProviderEnabled(String s) {
|
|
Log.d(TAG, "onProviderEnabled: ");
|
|
}
|
|
|
|
@Override
|
|
public void onProviderDisabled(String s) {
|
|
Log.d(TAG, "onProviderDisabled: ");
|
|
}
|
|
}
|
|
}
|
|
|