| 1 |
package ${packageName}; |
| 2 |
|
| 3 |
import android.animation.Animator; |
| 4 |
import android.animation.AnimatorListenerAdapter; |
| 5 |
import android.annotation.TargetApi; |
| 6 |
<#if !includeGooglePlus>import android.app.Activity;</#if> |
| 7 |
import android.app.LoaderManager.LoaderCallbacks; |
| 8 |
import android.content.ContentResolver; |
| 9 |
import android.content.CursorLoader; |
| 10 |
import android.content.Loader; |
| 11 |
import android.database.Cursor; |
| 12 |
import android.net.Uri; |
| 13 |
import android.os.AsyncTask; |
| 14 |
<#if minApiLevel lt 14>import android.os.Build.VERSION;</#if> |
| 15 |
import android.os.Build; |
| 16 |
import android.os.Bundle; |
| 17 |
import android.provider.ContactsContract; |
| 18 |
import android.text.TextUtils; |
| 19 |
import android.view.KeyEvent; |
| 20 |
import android.view.View; |
| 21 |
import android.view.View.OnClickListener; |
| 22 |
import android.view.inputmethod.EditorInfo; |
| 23 |
import android.widget.ArrayAdapter; |
| 24 |
import android.widget.AutoCompleteTextView; |
| 25 |
import android.widget.Button; |
| 26 |
import android.widget.EditText; |
| 27 |
import android.widget.TextView; |
| 28 |
<#if includeGooglePlus> |
| 29 |
import com.google.android.gms.common.ConnectionResult; |
| 30 |
import com.google.android.gms.common.GooglePlayServicesUtil; |
| 31 |
import com.google.android.gms.common.SignInButton; |
| 32 |
</#if> |
| 33 |
import java.util.ArrayList; |
| 34 |
import java.util.List; |
| 35 |
<#if applicationPackage??>import ${applicationPackage}.R;</#if> |
| 36 |
|
| 37 |
/** |
| 38 |
* A login screen that offers login via email/password<#if includeGooglePlus> and via Google+ sign in</#if>. |
| 39 |
<#if includeGooglePlus> * <p/> |
| 40 |
* ************ IMPORTANT SETUP NOTES: ************ |
| 41 |
* In order for Google+ sign in to work with your app, you must first go to: |
| 42 |
* https://developers.google.com/+/mobile/android/getting-started#step_1_enable_the_google_api |
| 43 |
* and follow the steps in "Step 1" to create an OAuth 2.0 client for your package.</#if> |
| 44 |
*/ |
| 45 |
public class ${activityClass} extends <#if includeGooglePlus>PlusBase</#if>Activity implements LoaderCallbacks<Cursor>{ |
| 46 |
|
| 47 |
/** |
| 48 |
* A dummy authentication store containing known user names and passwords. |
| 49 |
* TODO: remove after connecting to a real authentication system. |
| 50 |
*/ |
| 51 |
private static final String[] DUMMY_CREDENTIALS = new String[]{ |
| 52 |
"[email protected]:hello", "[email protected]:world" |
| 53 |
}; |
| 54 |
/** |
| 55 |
* Keep track of the login task to ensure we can cancel it if requested. |
| 56 |
*/ |
| 57 |
private UserLoginTask mAuthTask = null; |
| 58 |
|
| 59 |
// UI references. |
| 60 |
private AutoCompleteTextView mEmailView; |
| 61 |
private EditText mPasswordView; |
| 62 |
private View mProgressView;<#if includeGooglePlus> |
| 63 |
private View mEmailLoginFormView; |
| 64 |
private SignInButton mPlusSignInButton; |
| 65 |
private View mSignOutButtons;</#if> |
| 66 |
private View mLoginFormView; |
| 67 |
|
| 68 |
@Override |
| 69 |
protected void onCreate(Bundle savedInstanceState) { |
| 70 |
super.onCreate(savedInstanceState); |
| 71 |
setContentView(R.layout.activity_login); |
| 72 |
<#if parentActivityClass != ""> |
| 73 |
setupActionBar(); |
| 74 |
</#if> |
| 75 |
<#if includeGooglePlus> |
| 76 |
|
| 77 |
// Find the Google+ sign in button. |
| 78 |
mPlusSignInButton = (SignInButton) findViewById(R.id.plus_sign_in_button); |
| 79 |
if (supportsGooglePlayServices()) { |
| 80 |
// Set a listener to connect the user when the G+ button is clicked. |
| 81 |
mPlusSignInButton.setOnClickListener(new OnClickListener() { |
| 82 |
@Override |
| 83 |
public void onClick(View view) { |
| 84 |
signIn(); |
| 85 |
} |
| 86 |
}); |
| 87 |
} else { |
| 88 |
// Don't offer G+ sign in if the app's version is too low to support Google Play |
| 89 |
// Services. |
| 90 |
mPlusSignInButton.setVisibility(View.GONE); |
| 91 |
return; |
| 92 |
} |
| 93 |
</#if> |
| 94 |
|
| 95 |
// Set up the login form. |
| 96 |
mEmailView = (AutoCompleteTextView) findViewById(R.id.email); |
| 97 |
populateAutoComplete(); |
| 98 |
|
| 99 |
mPasswordView = (EditText) findViewById(R.id.password); |
| 100 |
mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() { |
| 101 |
@Override |
| 102 |
public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) { |
| 103 |
if (id == R.id.login || id == EditorInfo.IME_NULL) { |
| 104 |
attemptLogin(); |
| 105 |
return true; |
| 106 |
} |
| 107 |
return false; |
| 108 |
} |
| 109 |
}); |
| 110 |
|
| 111 |
Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button); |
| 112 |
mEmailSignInButton.setOnClickListener(new OnClickListener() { |
| 113 |
@Override |
| 114 |
public void onClick(View view) { |
| 115 |
attemptLogin(); |
| 116 |
} |
| 117 |
}); |
| 118 |
|
| 119 |
mLoginFormView = findViewById(R.id.login_form); |
| 120 |
mProgressView = findViewById(R.id.login_progress);<#if includeGooglePlus> |
| 121 |
mEmailLoginFormView = findViewById(R.id.email_login_form); |
| 122 |
mSignOutButtons = findViewById(R.id.plus_sign_out_buttons);</#if> |
| 123 |
} |
| 124 |
|
| 125 |
private void populateAutoComplete() { |
| 126 |
<#if minApiLevel gte 14> |
| 127 |
getLoaderManager().initLoader(0, null, this); |
| 128 |
<#else> |
| 129 |
if (VERSION.SDK_INT >= 14) { |
| 130 |
// Use ContactsContract.Profile (API 14+) |
| 131 |
getLoaderManager().initLoader(0, null, this); |
| 132 |
} else if (VERSION.SDK_INT >= 8) { |
| 133 |
// Use AccountManager (API 8+) |
| 134 |
new SetupEmailAutoCompleteTask().execute(null, null); |
| 135 |
} |
| 136 |
</#if> |
| 137 |
} |
| 138 |
|
| 139 |
<#if parentActivityClass != ""> |
| 140 |
/** |
| 141 |
* Set up the {@link android.app.ActionBar}, if the API is available. |
| 142 |
*/ |
| 143 |
@TargetApi(Build.VERSION_CODES.HONEYCOMB) |
| 144 |
private void setupActionBar() { |
| 145 |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { |
| 146 |
// Show the Up button in the action bar. |
| 147 |
getActionBar().setDisplayHomeAsUpEnabled(true); |
| 148 |
} |
| 149 |
} |
| 150 |
</#if> |
| 151 |
|
| 152 |
/** |
| 153 |
* Attempts to sign in or register the account specified by the login form. |
| 154 |
* If there are form errors (invalid email, missing fields, etc.), the |
| 155 |
* errors are presented and no actual login attempt is made. |
| 156 |
*/ |
| 157 |
public void attemptLogin() { |
| 158 |
if (mAuthTask != null) { |
| 159 |
return; |
| 160 |
} |
| 161 |
|
| 162 |
// Reset errors. |
| 163 |
mEmailView.setError(null); |
| 164 |
mPasswordView.setError(null); |
| 165 |
|
| 166 |
// Store values at the time of the login attempt. |
| 167 |
String email = mEmailView.getText().toString(); |
| 168 |
String password = mPasswordView.getText().toString(); |
| 169 |
|
| 170 |
boolean cancel = false; |
| 171 |
View focusView = null; |
| 172 |
|
| 173 |
// Check for a valid password, if the user entered one. |
| 174 |
if (!TextUtils.isEmpty(password) && !isPasswordValid(password)) { |
| 175 |
mPasswordView.setError(getString(R.string.error_invalid_password)); |
| 176 |
focusView = mPasswordView; |
| 177 |
cancel = true; |
| 178 |
} |
| 179 |
|
| 180 |
// Check for a valid email address. |
| 181 |
if (TextUtils.isEmpty(email)) { |
| 182 |
mEmailView.setError(getString(R.string.error_field_required)); |
| 183 |
focusView = mEmailView; |
| 184 |
cancel = true; |
| 185 |
} else if (!isEmailValid(email)) { |
| 186 |
mEmailView.setError(getString(R.string.error_invalid_email)); |
| 187 |
focusView = mEmailView; |
| 188 |
cancel = true; |
| 189 |
} |
| 190 |
|
| 191 |
if (cancel) { |
| 192 |
// There was an error; don't attempt login and focus the first |
| 193 |
// form field with an error. |
| 194 |
focusView.requestFocus(); |
| 195 |
} else { |
| 196 |
// Show a progress spinner, and kick off a background task to |
| 197 |
// perform the user login attempt. |
| 198 |
showProgress(true); |
| 199 |
mAuthTask = new UserLoginTask(email, password); |
| 200 |
mAuthTask.execute((Void) null); |
| 201 |
} |
| 202 |
} |
| 203 |
private boolean isEmailValid(String email) { |
| 204 |
//TODO: Replace this with your own logic |
| 205 |
return email.contains("@"); |
| 206 |
} |
| 207 |
|
| 208 |
private boolean isPasswordValid(String password) { |
| 209 |
//TODO: Replace this with your own logic |
| 210 |
return password.length() > 4; |
| 211 |
} |
| 212 |
|
| 213 |
/** |
| 214 |
* Shows the progress UI and hides the login form. |
| 215 |
*/ |
| 216 |
@TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2) |
| 217 |
public void showProgress(final boolean show) { |
| 218 |
// On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow |
| 219 |
// for very easy animations. If available, use these APIs to fade-in |
| 220 |
// the progress spinner. |
| 221 |
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) { |
| 222 |
int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime); |
| 223 |
|
| 224 |
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); |
| 225 |
mLoginFormView.animate().setDuration(shortAnimTime).alpha( |
| 226 |
show ? 0 : 1).setListener(new AnimatorListenerAdapter() { |
| 227 |
@Override |
| 228 |
public void onAnimationEnd(Animator animation) { |
| 229 |
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); |
| 230 |
} |
| 231 |
}); |
| 232 |
|
| 233 |
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); |
| 234 |
mProgressView.animate().setDuration(shortAnimTime).alpha( |
| 235 |
show ? 1 : 0).setListener(new AnimatorListenerAdapter() { |
| 236 |
@Override |
| 237 |
public void onAnimationEnd(Animator animation) { |
| 238 |
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); |
| 239 |
} |
| 240 |
}); |
| 241 |
} else { |
| 242 |
// The ViewPropertyAnimator APIs are not available, so simply show |
| 243 |
// and hide the relevant UI components. |
| 244 |
mProgressView.setVisibility(show ? View.VISIBLE : View.GONE); |
| 245 |
mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE); |
| 246 |
} |
| 247 |
} |
| 248 |
<#if includeGooglePlus> |
| 249 |
|
| 250 |
@Override |
| 251 |
protected void onPlusClientSignIn() { |
| 252 |
//Set up sign out and disconnect buttons. |
| 253 |
Button signOutButton = (Button) findViewById(R.id.plus_sign_out_button); |
| 254 |
signOutButton.setOnClickListener(new OnClickListener() { |
| 255 |
@Override |
| 256 |
public void onClick(View view) { |
| 257 |
signOut(); |
| 258 |
} |
| 259 |
}); |
| 260 |
Button disconnectButton = (Button) findViewById(R.id.plus_disconnect_button); |
| 261 |
disconnectButton.setOnClickListener(new OnClickListener() { |
| 262 |
@Override |
| 263 |
public void onClick(View view) { |
| 264 |
revokeAccess(); |
| 265 |
} |
| 266 |
}); |
| 267 |
} |
| 268 |
|
| 269 |
@Override |
| 270 |
protected void onPlusClientBlockingUI(boolean show) { |
| 271 |
showProgress(show); |
| 272 |
} |
| 273 |
|
| 274 |
@Override |
| 275 |
protected void updateConnectButtonState() { |
| 276 |
//TODO: Update this logic to also handle the user logged in by email. |
| 277 |
boolean connected = getPlusClient().isConnected(); |
| 278 |
|
| 279 |
mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE); |
| 280 |
mPlusSignInButton.setVisibility(connected ? View.GONE : View.VISIBLE); |
| 281 |
mEmailLoginFormView.setVisibility(connected ? View.GONE : View.VISIBLE); |
| 282 |
} |
| 283 |
|
| 284 |
@Override |
| 285 |
protected void onPlusClientRevokeAccess() { |
| 286 |
// TODO: Access to the user's G+ account has been revoked. Per the developer terms, delete |
| 287 |
// any stored user data here. |
| 288 |
} |
| 289 |
|
| 290 |
@Override |
| 291 |
protected void onPlusClientSignOut() { |
| 292 |
|
| 293 |
} |
| 294 |
|
| 295 |
/** |
| 296 |
* Check if the device supports Google Play Services. It's best |
| 297 |
* practice to check first rather than handling this as an error case. |
| 298 |
* |
| 299 |
* @return whether the device supports Google Play Services |
| 300 |
*/ |
| 301 |
private boolean supportsGooglePlayServices() { |
| 302 |
return GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == |
| 303 |
ConnectionResult.SUCCESS; |
| 304 |
} |
| 305 |
</#if> |
| 306 |
|
| 307 |
@Override |
| 308 |
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) { |
| 309 |
return new CursorLoader(this, |
| 310 |
// Retrieve data rows for the device user's 'profile' contact. |
| 311 |
Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI, |
| 312 |
ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION, |
| 313 |
|
| 314 |
// Select only email addresses. |
| 315 |
ContactsContract.Contacts.Data.MIMETYPE + |
| 316 |
" = ?", new String[]{ContactsContract.CommonDataKinds.Email |
| 317 |
.CONTENT_ITEM_TYPE}, |
| 318 |
|
| 319 |
// Show primary email addresses first. Note that there won't be |
| 320 |
// a primary email address if the user hasn't specified one. |
| 321 |
ContactsContract.Contacts.Data.IS_PRIMARY + " DESC"); |
| 322 |
} |
| 323 |
|
| 324 |
@Override |
| 325 |
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) { |
| 326 |
List<String> emails = new ArrayList<String>(); |
| 327 |
cursor.moveToFirst(); |
| 328 |
while (!cursor.isAfterLast()) { |
| 329 |
emails.add(cursor.getString(ProfileQuery.ADDRESS)); |
| 330 |
cursor.moveToNext(); |
| 331 |
} |
| 332 |
|
| 333 |
addEmailsToAutoComplete(emails); |
| 334 |
} |
| 335 |
|
| 336 |
@Override |
| 337 |
public void onLoaderReset(Loader<Cursor> cursorLoader) { |
| 338 |
|
| 339 |
} |
| 340 |
|
| 341 |
private interface ProfileQuery { |
| 342 |
String[] PROJECTION = { |
| 343 |
ContactsContract.CommonDataKinds.Email.ADDRESS, |
| 344 |
ContactsContract.CommonDataKinds.Email.IS_PRIMARY, |
| 345 |
}; |
| 346 |
|
| 347 |
int ADDRESS = 0; |
| 348 |
int IS_PRIMARY = 1; |
| 349 |
} |
| 350 |
|
| 351 |
<#if minApiLevel lt 14> |
| 352 |
/** |
| 353 |
* Use an AsyncTask to fetch the user's email addresses on a background thread, and update |
| 354 |
* the email text field with results on the main UI thread. |
| 355 |
*/ |
| 356 |
class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> { |
| 357 |
|
| 358 |
@Override |
| 359 |
protected List<String> doInBackground(Void... voids) { |
| 360 |
ArrayList<String> emailAddressCollection = new ArrayList<String>(); |
| 361 |
|
| 362 |
// Get all emails from the user's contacts and copy them to a list. |
| 363 |
ContentResolver cr = getContentResolver(); |
| 364 |
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, |
| 365 |
null, null, null); |
| 366 |
while (emailCur.moveToNext()) { |
| 367 |
String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract |
| 368 |
.CommonDataKinds.Email.DATA)); |
| 369 |
emailAddressCollection.add(email); |
| 370 |
} |
| 371 |
emailCur.close(); |
| 372 |
|
| 373 |
return emailAddressCollection; |
| 374 |
} |
| 375 |
|
| 376 |
@Override |
| 377 |
protected void onPostExecute(List<String> emailAddressCollection) { |
| 378 |
addEmailsToAutoComplete(emailAddressCollection); |
| 379 |
} |
| 380 |
} |
| 381 |
</#if> |
| 382 |
|
| 383 |
private void addEmailsToAutoComplete(List<String> emailAddressCollection) { |
| 384 |
//Create adapter to tell the AutoCompleteTextView what to show in its dropdown list. |
| 385 |
ArrayAdapter<String> adapter = |
| 386 |
new ArrayAdapter<String>(LoginActivity.this, |
| 387 |
android.R.layout.simple_dropdown_item_1line, emailAddressCollection); |
| 388 |
|
| 389 |
mEmailView.setAdapter(adapter); |
| 390 |
} |
| 391 |
|
| 392 |
/** |
| 393 |
* Represents an asynchronous login/registration task used to authenticate |
| 394 |
* the user. |
| 395 |
*/ |
| 396 |
public class UserLoginTask extends AsyncTask<Void, Void, Boolean> { |
| 397 |
|
| 398 |
private final String mEmail; |
| 399 |
private final String mPassword; |
| 400 |
|
| 401 |
UserLoginTask(String email, String password) { |
| 402 |
mEmail = email; |
| 403 |
mPassword = password; |
| 404 |
} |
| 405 |
|
| 406 |
@Override |
| 407 |
protected Boolean doInBackground(Void... params) { |
| 408 |
// TODO: attempt authentication against a network service. |
| 409 |
|
| 410 |
try { |
| 411 |
// Simulate network access. |
| 412 |
Thread.sleep(2000); |
| 413 |
} catch (InterruptedException e) { |
| 414 |
return false; |
| 415 |
} |
| 416 |
|
| 417 |
for (String credential : DUMMY_CREDENTIALS) { |
| 418 |
String[] pieces = credential.split(":"); |
| 419 |
if (pieces[0].equals(mEmail)) { |
| 420 |
// Account exists, return true if the password matches. |
| 421 |
return pieces[1].equals(mPassword); |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
// TODO: register the new account here. |
| 426 |
return true; |
| 427 |
} |
| 428 |
|
| 429 |
@Override |
| 430 |
protected void onPostExecute(final Boolean success) { |
| 431 |
mAuthTask = null; |
| 432 |
showProgress(false); |
| 433 |
|
| 434 |
if (success) { |
| 435 |
finish(); |
| 436 |
} else { |
| 437 |
mPasswordView.setError(getString(R.string.error_incorrect_password)); |
| 438 |
mPasswordView.requestFocus(); |
| 439 |
} |
| 440 |
} |
| 441 |
|
| 442 |
@Override |
| 443 |
protected void onCancelled() { |
| 444 |
mAuthTask = null; |
| 445 |
showProgress(false); |
| 446 |
} |
| 447 |
} |
| 448 |
} |
| 449 |
|