我正在开发一个应用程序,用户登录并登录。当用户登录时,我会记住,他的令牌是rememberede,当他再次点击app时,他不必去LogIn活动。但是,问题是当我登录他时,他进入LogIn活动但是当他退出LogIn活动并且当他再次点击app时,他直接进入主活动,因此他的令牌不会被删除。如何解决? 这是我的LogIn活动:
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();
}
}
});
这是我的主要活动:
@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();}
这是我LogOut按钮的逻辑(它在Main活动的片段上):
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();
}
});
我的清单:
<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>
有人可以帮助我吗?
答案 0 :(得分:1)
从
更改您的buttonOk onclick Listener linesharedPreferences.edit().remove("token").apply();
到
sharedPreferences.edit().remove("token").commit();
答案 1 :(得分:0)
您的SharedPreferences名称不同,其中包括#34; Token pref&#34;和其他是#34;令牌首选项#34;