1 package ${packageName};
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;
33 import java.util.ArrayList;
34 import java.util.List;
35 <#if applicationPackage??>import ${applicationPackage}.R;</#if>
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>
45 public class ${activityClass} extends <#if includeGooglePlus>PlusBase</#if>Activity implements LoaderCallbacks<Cursor>{
48 * A dummy authentication store containing known user names and passwords.
49 * TODO: remove after connecting to a real authentication system.
51 private static final String[] DUMMY_CREDENTIALS = new String[]{
52 "foo@example.com:hello", "bar@example.com:world"
55 * Keep track of the login task to ensure we can cancel it if requested.
57 private UserLoginTask mAuthTask = null;
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;
69 protected void onCreate(Bundle savedInstanceState) {
70 super.onCreate(savedInstanceState);
71 setContentView(R.layout.activity_login);
72 <#if parentActivityClass != "">
75 <#if includeGooglePlus>
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() {
83 public void onClick(View view) {
88 // Don't offer G+ sign in if the app's version is too low to support Google Play
90 mPlusSignInButton.setVisibility(View.GONE);
95 // Set up the login form.
96 mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
97 populateAutoComplete();
99 mPasswordView = (EditText) findViewById(R.id.password);
100 mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
102 public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
103 if (id == R.id.login || id == EditorInfo.IME_NULL) {
111 Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
112 mEmailSignInButton.setOnClickListener(new OnClickListener() {
114 public void onClick(View view) {
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>
125 private void populateAutoComplete() {
126 <#if minApiLevel gte 14>
127 getLoaderManager().initLoader(0, null, this);
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);
139 <#if parentActivityClass != "">
141 * Set up the {@link android.app.ActionBar}, if the API is available.
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);
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.
157 public void attemptLogin() {
158 if (mAuthTask != null) {
163 mEmailView.setError(null);
164 mPasswordView.setError(null);
166 // Store values at the time of the login attempt.
167 String email = mEmailView.getText().toString();
168 String password = mPasswordView.getText().toString();
170 boolean cancel = false;
171 View focusView = null;
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;
180 // Check for a valid email address.
181 if (TextUtils.isEmpty(email)) {
182 mEmailView.setError(getString(R.string.error_field_required));
183 focusView = mEmailView;
185 } else if (!isEmailValid(email)) {
186 mEmailView.setError(getString(R.string.error_invalid_email));
187 focusView = mEmailView;
192 // There was an error; don't attempt login and focus the first
193 // form field with an error.
194 focusView.requestFocus();
196 // Show a progress spinner, and kick off a background task to
197 // perform the user login attempt.
199 mAuthTask = new UserLoginTask(email, password);
200 mAuthTask.execute((Void) null);
203 private boolean isEmailValid(String email) {
204 //TODO: Replace this with your own logic
205 return email.contains("@");
208 private boolean isPasswordValid(String password) {
209 //TODO: Replace this with your own logic
210 return password.length() > 4;
214 * Shows the progress UI and hides the login form.
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);
224 mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
225 mLoginFormView.animate().setDuration(shortAnimTime).alpha(
226 show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
228 public void onAnimationEnd(Animator animation) {
229 mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
233 mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
234 mProgressView.animate().setDuration(shortAnimTime).alpha(
235 show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
237 public void onAnimationEnd(Animator animation) {
238 mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
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);
248 <#if includeGooglePlus>
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() {
256 public void onClick(View view) {
260 Button disconnectButton = (Button) findViewById(R.id.plus_disconnect_button);
261 disconnectButton.setOnClickListener(new OnClickListener() {
263 public void onClick(View view) {
270 protected void onPlusClientBlockingUI(boolean show) {
275 protected void updateConnectButtonState() {
276 //TODO: Update this logic to also handle the user logged in by email.
277 boolean connected = getPlusClient().isConnected();
279 mSignOutButtons.setVisibility(connected ? View.VISIBLE : View.GONE);
280 mPlusSignInButton.setVisibility(connected ? View.GONE : View.VISIBLE);
281 mEmailLoginFormView.setVisibility(connected ? View.GONE : View.VISIBLE);
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.
291 protected void onPlusClientSignOut() {
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.
299 * @return whether the device supports Google Play Services
301 private boolean supportsGooglePlayServices() {
302 return GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) ==
303 ConnectionResult.SUCCESS;
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,
314 // Select only email addresses.
315 ContactsContract.Contacts.Data.MIMETYPE +
316 " = ?", new String[]{ContactsContract.CommonDataKinds.Email
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");
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));
333 addEmailsToAutoComplete(emails);
337 public void onLoaderReset(Loader<Cursor> cursorLoader) {
341 private interface ProfileQuery {
342 String[] PROJECTION = {
343 ContactsContract.CommonDataKinds.Email.ADDRESS,
344 ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
351 <#if minApiLevel lt 14>
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.
356 class SetupEmailAutoCompleteTask extends AsyncTask<Void, Void, List<String>> {
359 protected List<String> doInBackground(Void... voids) {
360 ArrayList<String> emailAddressCollection = new ArrayList<String>();
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,
366 while (emailCur.moveToNext()) {
367 String email = emailCur.getString(emailCur.getColumnIndex(ContactsContract
368 .CommonDataKinds.Email.DATA));
369 emailAddressCollection.add(email);
373 return emailAddressCollection;
377 protected void onPostExecute(List<String> emailAddressCollection) {
378 addEmailsToAutoComplete(emailAddressCollection);
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);
389 mEmailView.setAdapter(adapter);
393 * Represents an asynchronous login/registration task used to authenticate
396 public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
398 private final String mEmail;
399 private final String mPassword;
401 UserLoginTask(String email, String password) {
403 mPassword = password;
407 protected Boolean doInBackground(Void... params) {
408 // TODO: attempt authentication against a network service.
411 // Simulate network access.
413 } catch (InterruptedException e) {
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);
425 // TODO: register the new account here.
430 protected void onPostExecute(final Boolean success) {
437 mPasswordView.setError(getString(R.string.error_incorrect_password));
438 mPasswordView.requestFocus();
443 protected void onCancelled() {