Когда пользователь входит в мое приложение для Android, я сохраняю сервер, возвращает токен в общих настройках и очищаю его только при выходе. Но когда я закрываю приложение через некоторое время, требуется повторный вход в систему. Вот мой общий класс настроек
package com.example.narmail.truck30mint.Api.models.UserModels;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class User {
public static SharedPreferences sharedPreferences;
Context context;
@SerializedName("token")
@Expose
private static String token;
/**
* No args constructor for use in serialization
*
*/
public User(Context context) {
super();
this.context = context;
sharedPreferences = context.getSharedPreferences("user_token",Context.MODE_PRIVATE);
}
/**
*
* @param //token
*/
/* public User(String token) {
super();
this.token = token;
}*/
public static String getToken() {
if(sharedPreferences.getString(token,null) != null){
token = sharedPreferences.getString(token,null);
};
return token;
}
public void setToken(String token) {
this.token = token;
sharedPreferences.edit().putString("token",token).apply();
}
public static void removeToken(){
if(sharedPreferences.contains("token")){
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.remove("token").commit();
token = null; //Missing this
System.out.println("shared preference deleting ");
}else{
System.out.println("not contain key token ");
}
}
}
а вот основное действие, которое проверяет, хранится ли токен в общих настройках
package com.example.narmail.truck30mint.Api.Activities;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.example.narmail.truck30mint.Api.models.UserModels.User;
import com.example.narmail.truck30mint.R;
public class MainActivity extends AppCompatActivity {
public String token = null;
private Context context;
public static Activity activity = null;
//save the context received via constructor in a local variable
/* public MainActivity(Context context) {
this.context = context;
}*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
User user = new User(getApplicationContext());
activity = this;
token = user.getToken();
System.out.println("in main activity token is "+token);
if (token != null && !token.equalsIgnoreCase("")) {
Intent a = new Intent(MainActivity.this, DashboardActivity.class);
startActivity(a);
}else if(token == null){
setContentView(R.layout.activity_main);
Button btnNewUser = findViewById(R.id.newUser);
Button btnExistingUser = findViewById(R.id.existingUser);
btnExistingUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent a = new Intent(MainActivity.this, LoginActivity.class);
startActivity(a);
// MainActivity.this.finish();
}
});
btnNewUser.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, RegisterActivity.class);
startActivity(i);
// MainActivity.this.finish();
}
});
}
// Acquire a reference to the system Location Manager
LocationManager locationManager =
(LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
String lat = Double.toString(location.getLatitude());
String lon = Double.toString(location.getLongitude());
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
/* if(checkPermission(Location,
android.Manifest.permission.ACCESS_FINE_LOCATION)){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}*/
// Register the listener with the Location Manager to receive location updates
}
}
при успешном входе в систему я сохраняю общие настройки этим методом
User user= new User(loginContext);
user.setToken(token);