The best way to store your Token
is when the user is successfully connected, that is, when Token
has already been successfully created. After that, just save Token
.
For example, the user logged in to LoginActivity
and was redirected to HomeActivity
, then ...
Home Activity
public class HomeActivity extends Activity {
SharedPreferences mPref = null;
@Override
public void onCreate (Bundle cicle) {
super.onCreate(cicle);
setContentView(R.layout.activity_home.xml); // Layout
// SharedPreferences
mPref = getSharedPreferences("tokenId", MODE_PRIVATE);
}
@Override
public void onResume () {
super.onResume();
mPref.edit().putInt("tokenId", "9102887").apply();
}
}
Login Activity
public class LoginActivity extends Activity {
SharedPreferences mPref = null;
@Override
public void onCreate (Bundle cicle) {
super.onCreate(cicle);
setContentView(R.layout.activity_home.xml); // Layout
// SharedPreferences
mPref = getSharedPreferences("tokenId", MODE_PRIVATE);
}
@Override
public void onResume () {
super.onResume();
// Se o token não for encontrado, o valor será 0
int token = mPref.getInt("tokenId", 0);
// Envia um pedido de token pro servidor
// recebe o token e compara com o token salvo
// se forem semelhantes, entra na conta direto
int tokenServer = webS.getToken(deviceId, user, pass);
if(token == tokenServer) // sucesso
}
}
You do not necessarily need to save Token
as Int
. It was just an example, I think the recommended one for your case is String
same. And it does not change much, just from putInt
to putString
. See the documentation .
Source : SharedPreferences