mf.stickybit.android.trackergps.LoginActivity.java Source code

Java tutorial

Introduction

Here is the source code for mf.stickybit.android.trackergps.LoginActivity.java

Source

package mf.stickybit.android.trackergps;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Matias Emanuel Ferrigno on 16 jun 2015.
 * e-mail: meferrigno [at] gmail.com
 * <p/>
 * Copyright 2015 Matias Emanuel Ferrigno [meferrigno@gmail.com]
 * <p/>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p/>
 * http://www.apache.org/licenses/LICENSE-2.00
 * <p/>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
public class LoginActivity extends Activity {

    // AsyncTask
    public UserLoginTask mAuthTask = null;

    // Referencias Interface
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private Button mEmailSignInButton;

    // Aux. Vars
    public int cantidadFails = 0; // cant. intentos fallidos.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // setup interface
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        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;
            }
        });
        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);

        // cantidad de fails en 0
        setCantidadFails(0);

    }

    @Override
    protected void onResume() {
        super.onResume();
        clear();
    }

    @Override
    public void finish() {
        super.finish();
        stopService(new Intent(this, TrackerGpsService.class));
        System.exit(0);
    }

    private void clear() {
        /*
        Reseteamos los valores de los textbox y limpiamos la vars
        usuario y eventos.
         */
        mEmailView.setText("");
        mPasswordView.setText("");
        TrackerGpsService.USUARIO = null;
        TrackerGpsService.EVENTOS = new ArrayList<Evento>();
    }

    public void onBackPressed() {
        finish();
    }

    public 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();

        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_incorrect_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(this, email, password);
            mAuthTask.execute((Void) null);
        }

    }

    public void setCantidadFails(int cantidadFails) {
        cantidadFails = cantidadFails;
    }

    public int getCantidadFails() {
        return cantidadFails;
    }

    public void checkLogin(boolean isLogin) {
        if (isLogin) {
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.cancelAll();
            final Intent notificationIntent = new Intent(this, MainActivity.class);
            notificationIntent.setAction(Intent.ACTION_MAIN);
            notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
            Notification notification = new NotificationCompat.Builder(this)
                    .setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, 0))
                    .setSmallIcon(R.drawable.trackergps_icon)
                    .setLargeIcon(BitmapFactory.decodeResource(this.getResources(), R.drawable.trackergps_icon))
                    .setTicker("TrackerGPS").setWhen(System.currentTimeMillis()).setAutoCancel(false)
                    .setContentTitle("TrackerGPS esta ejecutandose").setContentText("A la espera...").build();
            notification.flags |= Notification.FLAG_NO_CLEAR;
            notificationManager.notify(0, notification);

            moveTaskToBack(true);
        } else {
            if ((getCantidadFails() == (getResources().getInteger(R.integer.login_max_retry)))) {
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setMessage("Fallo "
                        + String.valueOf(
                                (int) getApplicationContext().getResources().getInteger(R.integer.login_max_retry))
                        + " veces al iniciar sesin.")
                        .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                finish();
                            }
                        });
                builder.show();
            } else {
                clear();
                mPasswordView.setError(getString(R.string.error_incorrect_password));
                mPasswordView.requestFocus();
            }

        }
    }

    // Validador email
    private boolean isEmailValid(String email) {
        return email.contains("@");
    }

    // Validador password
    private boolean isPasswordValid(String password) {
        return password.length() > 0;
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    public 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);
        }
    }

}