安卓登录的解决方案(记住密码)

安卓登录解决方案

在安卓开发中,肯定少不了登录,前几天写了个登录的demo,就想着记录下来,是新手,写的可能不太好,但是能用,以后写登录的时候直接copy不就好了么哈哈哈哈哈O(∩_∩)O~

Emmm,先上代码吧

LoginActivity

public class LoginActivity extends Activity implements View.OnClickListener {

    private SharedPreferences sp;
    private SharedPreferences.Editor editor;

    private ProgressBar processBar;
    private AutoCompleteTextView autoUsername;
    private EditText editTextPassword;
    private Button btnSignIn;
    private Button btnSignUp;
    private CheckBox checkBox;

    public static int LOG_OUT = 0;		//注销登录标识

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

        sp = PreferenceManager.getDefaultSharedPreferences(this);//获取SharedPreferences

        processBar =(ProgressBar) findViewById(R.id.login_progress);
        autoUsername = (AutoCompleteTextView) findViewById(R.id.username);
        editTextPassword = (EditText) findViewById(R.id.password);
        btnSignIn = (Button) findViewById(R.id.sign_in_button);
        btnSignUp = (Button) findViewById(R.id.sign_up_button);
        checkBox = (CheckBox)findViewById(R.id.rem_for_password);


        btnSignIn.setOnClickListener(this);
        btnSignUp.setOnClickListener(this);

        boolean isRemember = sp.getBoolean("remember_password",false);      //在SharedPreferences中获取是否记住密码
        if(getIntent().getFlags() == LOG_OUT){		//若是注销登录,那就不要记住密码了是吧
            isRemember = false;
        }
        if (isRemember){        //若记住密码,则在SharedPreferences中获取进行自动登录
            String username = sp.getString("username","");
            String password = sp.getString("password","");
            autoUsername.setText(username);
            editTextPassword.setText(password);
            checkBox.setChecked(true);

            //记住密码自动登录
            doLogin(username,password);
        }

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.sign_in_button:
                if(!processBar.isShown()){
                    processBar.setVisibility(View.VISIBLE);
                }
                String username = autoUsername.getText().toString();
                String password = editTextPassword.getText().toString();

                doLogin(username,password);
                break;
            case R.id.sign_up_button:
                Intent intent = new Intent(LoginActivity.this,SignUpActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    //登录
    private void doLogin(String username, String password) {

        editor = sp.edit();
        if(checkBox.isChecked()){       //若勾选记住密码,则在登录的时候将密码保存到SharedPreferences中
            editor.putBoolean("remember_password",true);
            editor.putString("username",username);
            editor.putString("password",password);
        }else {
            editor.clear();     //否则清空
        }
        editor.apply();

        //登录请求(RetrofitFactory是自己封装的网络请求工具,别到时候啥都复制不能用)
        RetrofitFactory.getInstance()
                .getService(UserService.class)
                .login(username, password)
                .enqueue(new Callback<SigninResponse>() {
                    @Override
                    public void onResponse(Call<SigninResponse> call, Response<SigninResponse> response) {
                        String name = response.body().getResult().getName();
                        Toast.makeText(LoginActivity.this,"登录成功,欢迎"+name,Toast.LENGTH_SHORT).show();
                        MyApplication.setUser(response.body().getResult());
                        if(processBar.isShown())
                            processBar.setVisibility(View.GONE);
                        Intent intent = new Intent(LoginActivity.this,MainActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Call<SigninResponse> call, Throwable t) {
                        if(processBar.isShown())
                            processBar.setVisibility(View.GONE);
                        Toast.makeText(LoginActivity.this,"登录失败,请检查您的账户或者密码重新登录",Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

activity_login.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

    <!-- 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" />

    <ScrollView
        android:id="@+id/login_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:id="@+id/email_login_form"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <AutoCompleteTextView
                android:id="@+id/username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_email"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

            <LinearLayout
                android:orientation="horizontal"
                android:layout_width="match_parent"
                android:layout_height="wrap_content">


                <Button
                    android:id="@+id/sign_in_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_weight="1"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_sign_in"
                    android:textStyle="bold" />

                <Button
                    android:id="@+id/sign_up_button"
                    style="?android:textAppearanceSmall"
                    android:layout_width="0dp"
                    android:layout_weight="1"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="16dp"
                    android:text="@string/action_sign_up"
                    android:textStyle="bold" />

            </LinearLayout>

            <CheckBox
                android:id="@+id/rem_for_password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/rem_or_for"
                />


        </LinearLayout>
    </ScrollView>
</LinearLayout>

注销登录

//注销登录
        Button logOut = (Button) findViewById(R.id.btn_logout);
        logOut.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(UerInfoActivity.this);
                SharedPreferences.Editor editor  = sp.edit();
                editor.putBoolean("remember_password",false);
                editor.apply();
                Intent intent = new Intent(UerInfoActivity.this,LoginActivity.class);
                intent.setFlags(LOG_OUT);
                startActivity(intent);
                finish();
            }
        });

啊~都写到这了,索性把注册也撂这

SignUpActivity

public class SignUpActivity extends Activity {

    private ProgressBar signupProgress;
    private AutoCompleteTextView autoTextName;
    private EditText editTextPassword;
    private EditText editTextAge;
    private EditText editTextAddress;
    private Button btnSignUp;

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

        signupProgress =(ProgressBar) findViewById(R.id.sign_up_progress);
        autoTextName = (AutoCompleteTextView) findViewById(R.id.sign_up_username);
        editTextPassword = (EditText) findViewById(R.id.sign_up_password);
        editTextAge = (EditText) findViewById(R.id.sign_up_age);
        editTextAddress = (EditText)findViewById(R.id.sign_up_address);
        btnSignUp = (Button) findViewById(R.id.sign_up);
        btnSignUp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!signupProgress.isShown()){
                    signupProgress.setVisibility(View.VISIBLE);
                }
                doSignUp();
            }
        });
    }

    /**
     * 注册
     */
    public void doSignUp() {
        String username = autoTextName.getText().toString();
        String password = editTextPassword.getText().toString();
        String age = editTextAge.getText().toString();
        String address = editTextAddress.getText().toString();

        RetrofitFactory.getInstance()
                .getService(UserService.class)
                .toSign(username,password, Integer.parseInt(age),address)
                .enqueue(new Callback<SignUpResponse>() {
                    @Override
                    public void onResponse(Call<SignUpResponse> call, Response<SignUpResponse> response) {
                        Toast.makeText(SignUpActivity.this,"注册成功,去登录吧",Toast.LENGTH_SHORT).show();
                        if(signupProgress.isShown())
                            signupProgress.setVisibility(View.GONE);
                        //注册成功后跳转到登录界面
                        Intent intent = new Intent(SignUpActivity.this,LoginActivity.class);
                        startActivity(intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Call<SignUpResponse> call, Throwable t) {
                        if(signupProgress.isShown())
                            signupProgress.setVisibility(View.GONE);
                        Toast.makeText(SignUpActivity.this,"注册失败",Toast.LENGTH_SHORT).show();
                    }
                });
    }
}

activity_signup

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    >

    <!-- Login progress -->
    <ProgressBar
        android:id="@+id/sign_up_progress"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:visibility="gone" />

    <ScrollView
        android:id="@+id/sign_up_form"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <AutoCompleteTextView
                android:id="@+id/sign_up_username"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_email"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/sign_up_password"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_password"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:inputType="textPassword"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/sign_up_age"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_age"
                android:imeActionId="6"
                android:inputType="number"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:maxLines="1"
                android:singleLine="true" />

            <EditText
                android:id="@+id/sign_up_address"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/prompt_address"
                android:imeActionId="6"
                android:imeActionLabel="@string/action_sign_in_short"
                android:imeOptions="actionUnspecified"
                android:maxLines="1"
                android:singleLine="true" />

            <Button
                android:id="@+id/sign_up"
                style="?android:textAppearanceSmall"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="16dp"
                android:text="@string/action_sign_up"
                android:textStyle="bold" />

        </LinearLayout>
    </ScrollView>
</LinearLayout>

刺激刺激~写完就走

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值