Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package fabiohcnobre.jhotelcolonialdosnobres;
- import java.util.ArrayList;
- import java.util.List;
- import static android.Manifest.permission.READ_CONTACTS;
- /**
- * A login screen that offers login via email/password.
- */
- public class LoginActivity extends AppCompatActivity implements LoaderCallbacks<Cursor>, GoogleApiClient.OnConnectionFailedListener {
- /**
- * Id to identity READ_CONTACTS permission request.
- */
- private static final int REQUEST_READ_CONTACTS = 0;
- private static final int RC_SIGN_IN = 9001;
- /**
- * Keep track of the login task to ensure we can cancel it if requested.
- */
- // UI references.
- private AutoCompleteTextView mEmailView;
- private EditText mPasswordView;
- private View mProgressView;
- private View mLoginFormView;
- private FirebaseAuth mAuth;
- private FirebaseAuth.AuthStateListener mAuthListener;
- private String TAG;
- GoogleApiClient mGoogleApiClient;
- CallbackManager mCallbackManager;
- private GoogleApiClient client;
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.activity_login);
- Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
- setSupportActionBar(toolbar);
- getSupportActionBar().setDisplayHomeAsUpEnabled(true);
- // Set up the login form.
- mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
- GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
- .requestIdToken(getString(R.string.default_web_client_id))
- .requestEmail()
- .build();
- mGoogleApiClient = new GoogleApiClient.Builder(this)
- .enableAutoManage(this, this)
- .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
- .build();
- SignInButton signInButton = (SignInButton) findViewById(R.id.sign_in_button);
- signInButton.setSize(SignInButton.SIZE_STANDARD);
- signInButton.setScopes(gso.getScopeArray());
- signInButton.setOnClickListener(new OnClickListener() {
- @Override
- public void onClick(View v) {
- switch (v.getId()) {
- case R.id.sign_in_button:
- showProgress(true);
- signIn();
- break;
- // ...
- }
- }
- private void signIn() {
- Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
- startActivityForResult(signInIntent, RC_SIGN_IN);
- }
- });
- populateAutoComplete();
- mAuth = FirebaseAuth.getInstance();
- mAuthListener = new FirebaseAuth.AuthStateListener() {
- @Override
- public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
- FirebaseUser user = firebaseAuth.getCurrentUser();
- if (user != null) {
- // User is signed in
- Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
- } else {
- // User is signed out
- Log.d(TAG, "onAuthStateChanged:signed_out");
- }
- // ...
- }
- };
- FacebookSdk.sdkInitialize(getApplicationContext());
- mCallbackManager = CallbackManager.Factory.create();
- LoginManager.getInstance().registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
- @Override
- public void onSuccess(LoginResult loginResult) {
- showProgress(true);
- Log.d(TAG, "facebook:onSuccess:" + loginResult);
- handleFacebookAccessToken(loginResult.getAccessToken());
- }
- @Override
- public void onCancel() {
- Log.d(TAG, "facebook:onCancel");
- // ...
- }
- @Override
- public void onError(FacebookException error) {
- Log.d(TAG, "facebook:onError", error);
- // ...
- }
- });
- LoginButton loginButton = (LoginButton) findViewById(R.id.button_facebook_login);
- loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
- @Override
- public void onSuccess(LoginResult loginResult) {
- showProgress(true);
- Log.d(TAG, "facebook:onSuccess:" + loginResult);
- handleFacebookAccessToken(loginResult.getAccessToken());
- }
- @Override
- public void onCancel() {
- Log.d(TAG, "facebook:onCancel");
- // ...
- }
- @Override
- public void onError(FacebookException error) {
- Log.d(TAG, "facebook:onError", error);
- // ...
- }
- });
- 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);
- // ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
- }
- private void populateAutoComplete() {
- if (!mayRequestContacts()) {
- return;
- }
- getLoaderManager().initLoader(0, null, this);
- }
- 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.permission_rationale, Snackbar.LENGTH_INDEFINITE)
- .setAction(android.R.string.ok, new 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;
- }
- /**
- * 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();
- }
- }
- }
- /**
- * 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() {
- // 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();
- 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);
- mAuth.signInWithEmailAndPassword(email, password)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
- // If sign in fails, display a message to the user. If sign in succeeds
- // the auth state listener will be notified and logic to handle the
- // signed in user can be handled in the listener.
- if (!task.isSuccessful()) {
- Log.w(TAG, "signInWithEmail", task.getException());
- Toast.makeText(LoginActivity.this, "Authentication failed.",
- Toast.LENGTH_SHORT).show();
- showProgress(false);
- } else {
- Intent it = new Intent(LoginActivity.this, searchActivity.class);
- startActivity(it);
- }
- }
- });
- }
- }
- private boolean isEmailValid(String email) {
- //TODO: Replace this with your own logic
- return email.contains("@");
- }
- private boolean isPasswordValid(String password) {
- //TODO: Replace this with your own logic
- 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.
- if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
- 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);
- }
- });
- } else {
- // The ViewPropertyAnimator APIs are not available, so simply show
- // and hide the relevant UI components.
- mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
- mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
- }
- }
- @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);
- }
- /**
- * ATTENTION: This was auto-generated to implement the App Indexing API.
- * See https://g.co/AppIndexing/AndroidStudio for more information.
- */
- public Action getIndexApiAction() {
- Thing object = new Thing.Builder()
- .setName("Login Page") // TODO: Define a title for the content shown.
- // TODO: Make sure this auto-generated URL is correct.
- .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
- .build();
- return new Action.Builder(Action.TYPE_VIEW)
- .setObject(object)
- .setActionStatus(Action.STATUS_TYPE_COMPLETED)
- .build();
- }
- @Override
- public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
- }
- private interface ProfileQuery {
- String[] PROJECTION = {
- ContactsContract.CommonDataKinds.Email.ADDRESS,
- ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
- };
- int ADDRESS = 0;
- int IS_PRIMARY = 1;
- }
- @Override
- public void onStart() {
- super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- client.connect();
- mAuth.addAuthStateListener(mAuthListener);
- // ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- AppIndex.AppIndexApi.start(client, getIndexApiAction());
- //Login automatico com facebook
- // LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("public_profile"));
- }
- @Override
- public void onStop() {
- super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- AppIndex.AppIndexApi.end(client, getIndexApiAction());
- if (mAuthListener != null) {
- mAuth.removeAuthStateListener(mAuthListener);
- }
- // ATTENTION: This was auto-generated to implement the App Indexing API.
- // See https://g.co/AppIndexing/AndroidStudio for more information.
- LoginManager.getInstance().logOut();
- client.disconnect();
- }
- @Override
- public void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
- super.onActivityResult(requestCode, resultCode, data);
- // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
- if (requestCode == RC_SIGN_IN) {
- GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
- if (result.isSuccess()) {
- // Google Sign In was successful, authenticate with Firebase
- GoogleSignInAccount account = result.getSignInAccount();
- firebaseAuthWithGoogle(account);
- } else {
- Toast.makeText(LoginActivity.this, "Falha Google",
- Toast.LENGTH_SHORT).show();
- }
- }else {
- mCallbackManager.onActivityResult(requestCode, resultCode, data);
- }
- }
- private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
- Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
- AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
- // If sign in fails, display a message to the user. If sign in succeeds
- // the auth state listener will be notified and logic to handle the
- // signed in user can be handled in the listener.
- if (!task.isSuccessful()) {
- Log.w(TAG, "signInWithCredential", task.getException());
- Toast.makeText(LoginActivity.this, "Falha FireBase",
- Toast.LENGTH_SHORT).show();
- } else {
- Intent it = new Intent(LoginActivity.this, searchActivity.class);
- startActivity(it);
- }
- }
- });
- }
- private void handleFacebookAccessToken(AccessToken token) {
- Log.d(TAG, "handleFacebookAccessToken:" + token);
- AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
- mAuth.signInWithCredential(credential)
- .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
- @Override
- public void onComplete(@NonNull Task<AuthResult> task) {
- Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful());
- if (!task.isSuccessful()) {
- Log.w(TAG, "signInWithCredential", task.getException());
- Toast.makeText(LoginActivity.this, "Authentication failed.",
- Toast.LENGTH_SHORT).show();
- }else {
- Intent it = new Intent(LoginActivity.this, searchActivity.class);
- startActivity(it);
- }
- // ...
- }
- });
- }
- }
- <?xml version="1.0" encoding="utf-8"?><android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
- xmlns:app="http://schemas.android.com/apk/res-auto"
- xmlns:tools="http://schemas.android.com/tools"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:fitsSystemWindows="true"
- tools:context="fabiohcnobre.jhotelcolonialdosnobres.LoginActivity">
- <android.support.design.widget.AppBarLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:theme="@style/AppTheme.AppBarOverlay">
- <android.support.v7.widget.Toolbar
- android:id="@+id/toolbar"
- android:layout_width="match_parent"
- android:layout_height="?attr/actionBarSize"
- android:background="?attr/colorPrimary"
- app:popupTheme="@style/AppTheme.PopupOverlay" />
- </android.support.design.widget.AppBarLayout>
- <RelativeLayout
- android:layout_width="match_parent"
- android:layout_height="461dp"
- android:paddingBottom="@dimen/activity_vertical_margin"
- android:paddingLeft="@dimen/activity_horizontal_margin"
- android:paddingRight="@dimen/activity_horizontal_margin"
- android:paddingTop="@dimen/activity_vertical_margin"
- app:layout_behavior="@string/appbar_scrolling_view_behavior" >
- <LinearLayout
- android:orientation="vertical"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:layout_alignParentTop="true"
- android:layout_alignParentStart="true">
- <!-- Login progress -->
- <ProgressBar
- android:id="@+id/login_progress"
- style="?android:attr/progressBarStyleLarge"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:layout_marginBottom="8dp"
- android:visibility="gone"
- android:layout_gravity="center_horizontal"/>
- <TextView
- android:text="TextView"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:id="@+id/textView2" />
- <ScrollView
- android:id="@+id/login_form"
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <LinearLayout
- android:id="@+id/email_login_form"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <android.support.design.widget.TextInputLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <AutoCompleteTextView
- android:id="@+id/email"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="@string/prompt_email"
- android:inputType="textEmailAddress"
- android:maxLines="1"
- android:singleLine="true" />
- </android.support.design.widget.TextInputLayout>
- <android.support.design.widget.TextInputLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <EditText
- android:id="@+id/password"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:hint="@string/prompt_password"
- android:imeActionId="@+id/login"
- android:imeActionLabel="@string/action_sign_in_short"
- android:imeOptions="actionUnspecified"
- android:inputType="textPassword"
- android:maxLines="1"
- android:singleLine="true" />
- </android.support.design.widget.TextInputLayout>
- <Button
- android:id="@+id/email_sign_in_button"
- style="?android:textAppearanceSmall"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:layout_marginTop="16dp"
- android:text="@string/action_sign_in"
- android:textStyle="bold" />
- </LinearLayout>
- </ScrollView>
- <com.facebook.login.widget.LoginButton
- android:id="@+id/button_facebook_login"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- <com.google.android.gms.common.SignInButton
- android:id="@+id/sign_in_button"
- android:layout_width="match_parent"
- android:layout_height="wrap_content" />
- </LinearLayout>
- </RelativeLayout>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement