One way to do it is like this:
public class AtividadeInicial extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
exibeTelaPrincipalOuSolicitaLogin();
finish();
}
private void exibeTelaPrincipalOuSolicitaLogin() {
Intent intent = new Intent(this, usuárioEstáLogado() ? AtividadePrincipal.class : AtividadeLogin.class);
startActivity(intent);
}
private boolean usuárioEstáLogado() {
// Sua implementação que retorna se o usuário está logado ou não,
// obtida por exemplo verificando se o token de autenticação
// guardado em SharedPreferences é diferente de null.
}
}
If you preserve the authentication between calls to Web Services through a token with time to expire on the server, the login condition may no longer be valid if the user does not browse the application for long and the token expires. In that case it may be necessary to close all Activities
open and request login again, which can be done by calling the method efetuarLogoffEVoltarParaATelaDeLogin()
down below:
public abstract class AtividadeEmQueOUsuárioEstáLogado {
protected void efetuarLogoffEVoltarParaATelaDeLogin() {
invalidarTokenDeAutenticação();
fecharTodasAsTelasEAbrirTelaDeLogin();
}
private void invalidarTokenDeAutenticação() {
// Sua implementação que invalida o token atual
// (por exemplo setando-o para null)
}
private void fecharTodasAsTelasEAbrirTelaDeLogin() {
Intent intent = new Intent(this, AtividadeLogin.class); // ou AtividadeInicial.class
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
public class AtividadePrincipal extends AtividadeEmQueOUsuárioEstáLogado {
public métodoQualquer() {
if (chameiUmWebServiceEConstateiQueOTokenExpirou) {
efetuarLogoffEVoltarParaATelaDeLogin();
}
}
}
You may want to make the methods usuárioEstáLogado()
and invalidarTokenDeAutenticação()
globally accessible for use elsewhere, including in a conventional class or subclass of Application
and eventually making them static (static
).
Your question is very wide. Try to provide more details, such as what you have been able to encode so far, for more accurate answers.
– ptkato
Patrick, I made the Login screen and a Register screen, but talking to some friends and they told me that I was doing wrong when calling the login screen direct in the main Activity, I wanted the application to detect if the user is logged in... I believe that only a few tips on which sequence of activities is good for me...
– Israel Sousa