Я занимаюсь разработкой приложения для Android, в моем приложении есть вход в систему.Что я хочу сделать, так это то, что когда пользователь вошел в систему в первый раз, он останется в системе, даже если приложение будет закрыто.
Я пытался выйти, но это не сработало.Любая помощь будет оценена.Спасибо!
1) Login.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) Constants.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";
}
ОБНОВЛЕНИЕ
Login.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);
}
}