我正在开发一个让用户登录并登录的应用程序。当用户登录时,我会记住他的 token ,当他再次点击应用程序时,他不必去登录 Activity 。但是,问题是当我注销他时,他会转到登录 Activity ,但是当他退出登录 Activity 并再次单击应用程序时,他会直接转到主 Activity ,因此他的 token 不会被删除。如何解决? 这是我的登录 Activity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
credentials = new Credentials();
login = (Button) findViewById(R.id.btn_login);
login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
username = (TextInputEditText)findViewById(R.id.username);
password = (TextInputEditText)findViewById(R.id.password);
String getUsername = username.getText().toString();
String getPassword = password.getText().toString();
if (getUsername.length()>0 && getPassword.length()>0 ) {
credentials.setUsername(getUsername);
credentials.setPassword(getPassword);
allOperations();
} else {
Toast.makeText(LoginActivity.this, R.string.empty_fields , Toast.LENGTH_LONG).show();
}
}
});
这是我的主要 Activity :
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.tool_bar);
setSupportActionBar(toolbar);
SharedPreferences shf = getSharedPreferences("Token pref", MODE_PRIVATE);
final String strPref = shf.getString("token", null);
if(strPref == null) {
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
initializeInjector();
initialize();}
这是我的注销按钮逻辑(它在主要 Activity 的 fragment 上):
buttonOk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getActivity().getSharedPreferences("Token Prefs", Context.MODE_PRIVATE);
sharedPreferences.edit().remove("token").apply();
Intent intent = new Intent(context, LoginActivity.class);
startActivity(intent);
getActivity().finish();
}
});
还有我的 list :
<activity android:name=".view.activities.MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".view.activities.LoginActivity"
android:screenOrientation="portrait">
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
有人可以帮我吗?
最佳答案
改变你的 buttonOk onclick Listener line from
sharedPreferences.edit().remove("token").apply();
到
sharedPreferences.edit().remove("token").commit();
关于android - 为什么我的 token 没有被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38562279/