我正在尝试为我的应用创建一个登录屏幕,该登录屏幕在3次登录尝试失败后禁用登录按钮5分钟。
但是,在我的应用中,可以通过关闭应用并再次启动来轻松再次启用该按钮。
我该如何解决这个问题?
代码:
public class LogIn extends Activity {
EditText username = null;
EditText password = null;
Button loginbutton = null;
int counter = 2;
String user = "admin";
String pw = "password";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
loginbutton = (Button) findViewById(R.id.loginbutton);
loginbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{ String name = username.getText().toString();
String pass = password.getText().toString();
if (name.equals(user) && pass.equals(pw))
// Successful Login
{ Intent intent = new Intent(LogIn.this, MainApp.class);
startActivity(intent);
}
else if (name.equals("") || pass.equals(""))
// Missing username or password
{ Toast alert = Toast.makeText(LogIn.this, "Please enter a username or password", Toast.LENGTH_SHORT);
alert.show();
}
else if (counter == 0)
// Disable button after 3 failed attempts
{ loginbutton.setEnabled(false);
Toast alert = Toast.makeText(LogIn.this, "Login Disabled for 5 mins", Toast.LENGTH_SHORT);
alert.show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable()
{ @Override
public void run()
{ loginbutton.setEnabled(true);
counter = 2;
}
}, 300000);
}
else
// Wrong password
{ Toast alert = Toast.makeText(LogIn.this, "Wrong Credentials", Toast.LENGTH_SHORT);
alert.show();
counter--;
};
}
});
};
}
答案 0 :(得分:1)
您可以使用共享首选项来存储任何失败尝试。如果用户无法登录该应用程序,您可以在共享的首选项中存储该尝试的尝试次数和时间。
SharedPreferences pref = this.getSharedPreferences("Sample", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString("ATTEMPTs", "5");
editor.putString("ATTEMPT_Time", System.currentTimeMillis());
editor.commit();
启动登录活动时,请检查共享首选项中的尝试次数,并相应地启用或禁用登录按钮。
SharedPreferences pref = this.getSharedPreferences("Sample", Context.MODE_PRIVATE);
String no_attempt = pref.getString("ATTEMPTs", "");
String time= pref.getString("ATTEMPT_Time"," ");
if(no_attempt>5 && Long.parseLong(time)>(System.currentTimeMillis()-300000))
{
btn_login.setVisibilty(View.INVISIBLE);
}
else
{
//login
}
答案 1 :(得分:1)
在这种情况下,您可以将CurrentTime保存在首选项中,并在尝试重新登录之前进行检查
这是偏好的工作方式
// Initiate the preference with Preference Filename and Access Mode for other Apps
SharedPreferences pref = getSharedPreferences("LoginTrack", Context.MODE_PRIVATE); // "LoginTrack" is the preference Name
// read the preference
long l = prefs.getLong("LastLoginDateTime", new Date().getTime());
String Attempts= pref.getString("MaxAttempts", "");
//To edit and save preferences again when you try login
Date dt = new Date(); // Current Time to Track loginTime
prefs.edit().putLong("LastLoginDateTime", dt.getTime()).commit();
prefs.edit().putString("MaxAttempts", "5").commit();
检索数据后,根据需要进行验证