首页 > 解决方案 > 首次登录后尝试在我的 android 应用程序中保持用户登录但无法正常工作

问题描述

我正在开发一个 android 应用程序,我的应用程序有一个登录活动。我想要做的是,一旦用户第一次登录,即使应用程序关闭,它也会保持登录状态。

我尝试了一条出路,但效果不佳。任何帮助将不胜感激。谢谢!

1) 登录.java

private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mSubscriptions = new CompositeSubscription();
    mSubscriptions = new CompositeSubscription();

    loginUserName = (EditText) findViewById(R.id.email_edit);
    loginPassword = (EditText) findViewById(R.id.pass_edit);
    pd = new ProgressDialog(Login.this);
    mTiEmail = (TextInputLayout) findViewById(R.id.email1);
    mTiPassword = (TextInputLayout) findViewById(R.id.password);
    loginButton = (TextView)findViewById(R.id.btn_login);
    initSharedPreferences();
    loginButton.setOnClickListener(view -> login());

    }
    @Override
    protected void onResume() {
        super.onResume();
        //In onresume fetching value from sharedpreference
        SharedPreferences sharedPreferences = getSharedPreferences(Constants.SHARED_PREF_NAME, Context.MODE_PRIVATE);

        //Fetching the boolean value form sharedpreferences
        loggedIn = sharedPreferences.getBoolean(Constants.LOGGEDIN_SHARED_PREF, false);

        //If we will get true
        if (loggedIn) {
            //We will start the Profile Activity
            Intent intent = new Intent(Login.this, Dashboard.class);
            startActivity(intent);
        }
    }
private void initSharedPreferences() {

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {

    setError();

    String email = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    int err = 0;

    if (!validateEmail(email)) {

        err++;
        mTiEmail.setError("Email should be valid !");
    }

    if (!validateFields(password)) {

        err++;
        mTiPassword.setError("Password should not be empty !");
    }

    if (err == 0) {

        loginProcess(email,password);


    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }
}
private void setError() {

    loginUserName.setError(null);
    loginPassword.setError(null);
}
private void loginProcess(String email, String password) {

    mSubscriptions.add(NetworkUtil.getRetrofit(email,password).login()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(this::handleResponse,this::handleError));
}
private void handleResponse(Response response) {

    SharedPreferences.Editor editor = mSharedPreferences.edit();
    editor.putString(Constants.TOKEN,response.getToken());
    editor.putString(Constants.EMAIL,response.getMessage());
    editor.apply();

   loginUserName.setText(null);
    loginPassword.setText(null);
    Intent in = new Intent(Login.this,Dashboard.class);
    startActivity(in);
    Toast.makeText(this, "REGISTERED-->>", Toast.LENGTH_LONG).show();
}
private void handleError(Throwable error) {


    if (error instanceof HttpException) {

        Gson gson = new GsonBuilder().create();

        try {

            String errorBody = ((HttpException) error).response().errorBody().string();
            Response response = gson.fromJson(errorBody,Response.class);
            Toast.makeText(this, response.getMessage(), Toast.LENGTH_SHORT).show();

        } catch (IOException e) {
            e.printStackTrace();
        }
    } else {

        Toast.makeText(this, error.getMessage(), Toast.LENGTH_SHORT).show();
    }
}


}

在我的 onResume() 方法中,我尝试了一种方法但没有奏效,有什么建议吗?

2) 常量.java

public class Constants {

public static final String BASE_URL = "http://192.168.2.145:8080/api/v1/";
public static final String TOKEN = "token";
public static final String EMAIL = "email";
//This would be the name of our shared preferences
public static final String SHARED_PREF_NAME = "myloginapp";

//This would be used to store the email of current logged in user
public static final String EMAIL_SHARED_PREF = "email";

//We will use this to store the boolean in sharedpreference to track user is loggedin or not
public static final String LOGGEDIN_SHARED_PREF = "loggedin";

}

更新

登录.java

public class Login extends AppCompatActivity {
TextView loginButton;
EditText loginUserName, loginPassword;

private Snackbar snackbar;
private ProgressDialog pd;
private TextInputLayout mTiEmail;
private TextInputLayout mTiPassword;
private CompositeSubscription mSubscriptions;
private SharedPreferences mSharedPreferences;
private Boolean loggedIn = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    mSubscriptions = new CompositeSubscription();
    mSubscriptions = new CompositeSubscription();

    loginUserName = (EditText) findViewById(R.id.email_edit);
    loginPassword = (EditText) findViewById(R.id.pass_edit);
    pd = new ProgressDialog(Login.this);
    mTiEmail = (TextInputLayout) findViewById(R.id.email1);
    mTiPassword = (TextInputLayout) findViewById(R.id.password);
    loginButton = (TextView)findViewById(R.id.btn_login);
    initSharedPreferences();
    loginButton.setOnClickListener(view -> login());

    }
@Override
protected void onResume() {
    super.onResume();
    //In onresume fetching value from sharedpreference
    mSharedPreferences = getSharedPreferences("login", Context.MODE_PRIVATE);
    if(mSharedPreferences.getBoolean("LoggedIn", false)){
        Intent intent = new Intent(Login.this,Dashboard.class);
        startActivity(intent);
    } else {
        loginButton.setOnClickListener(view -> login());

        //Do other stuff
    }
}
private void initSharedPreferences() {

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(Login.this);
}
private void login() {



    String username = loginUserName.getText().toString();
    String password = loginPassword.getText().toString();

    loginProcess(username,password);


    int err = 0;

    if (!validateFields(username)&& !validateFields(password)) {

        err++;
        mTiEmail.setError("Username should not be empty !");
    }



    if (err == 0) {

        loginProcess(username,password);


    } else {

        Toast.makeText(this, "Enter valid details", Toast.LENGTH_SHORT).show();
    }


}

private void loginProcess(String username,String password){

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    RetrofitInterface requestInterface = retrofit.create(RetrofitInterface.class);

    User user = new User();
    user.setUsername(username);
    user.setPassword(password);
    ServerRequest request = new ServerRequest();
    request.setOperation(Constants.LOGIN_OPERATION);
    request.setUser(user);
    Call<ServerResponse> response = requestInterface.operation(request);





    response.enqueue(new Callback<ServerResponse>() {
        @Override
        public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
            if(response.isSuccessful()) {
                ServerResponse serverResponse = response.body();
                if(serverResponse.getMessage().equals(Constants.SUCCESS)) {
                    SharedPreferences.Editor editor = mSharedPreferences.edit();
                    editor.putBoolean("LoggedIn",true);
                    //editor.putString(Constants.EMAIL,serverResponse.getUser().getEmail());
                    editor.putString(Constants.USERNAME,serverResponse.getUser().getUsername());
                    editor.putString(Constants.BUSINESSNAME,serverResponse.getUser().getBusinessname());
                    editor.apply();



                    Toast.makeText(Login.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
                    goToProfile();
                } else {
                    Toast.makeText(Login.this, serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                }
            } else {
                Gson gson = new Gson();
                ServerResponse errorResponse = null;
                try {
                    errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                Toast.makeText(Login.this, errorResponse.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onFailure(Call<ServerResponse> call, Throwable t) {


            Log.d(Constants.TAG,"failed");
            Toast.makeText(Login.this,t.getLocalizedMessage() , Toast.LENGTH_SHORT).show();
        }
    });
}



private void goToProfile(){

    Intent intent = new Intent(this,Dashboard.class);
    startActivity(intent);
}

}

标签: androidloginsharedpreferences

解决方案


将此代码放入您的 onCreate()

SharedPreferences pref = getSharedPrefrences("login", Context.MODE_PRIVATE); //Opening 'login' sharedPreference 
if(pref.getBoolean("LoggedIn", false)){ //checking if 'LoggedIn' exist in SharedPreference if no exist it returns false. if it exist fetches its value
   //Move to Next Screen
} else {
   loginButton.setOnClickListener(view -> login());
   //Do other stuff
}

然后在你的 handleResponse().. 添加这些行

//Lets suppose if User is logging in for the First time.. Below lines will add 'LoggedIn' to shared preference so user logged in directly next time

   SharedPreferences.Editor editor = pref.edit();
   editor.putBoolean("LoggedIn", true);
   editor.apply();

推荐阅读