Debian Codegraph @

templates/activities/LoginActivity/root/src/app_package/LoginActivity.java.ftl

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