Java 根据国际时间禁用按钮6小时
我对安卓非常陌生。我想在按下按钮后禁用它,并在6小时/1天后根据系统时间重新启用它。这就像每天给用户奖励一样。用户一天只能按一次奖励按钮。Java 根据国际时间禁用按钮6小时,java,android,button,Java,Android,Button,我对安卓非常陌生。我想在按下按钮后禁用它,并在6小时/1天后根据系统时间重新启用它。这就像每天给用户奖励一样。用户一天只能按一次奖励按钮。 当我在6小时前重新打开应用程序时,该按钮将再次启用。请帮忙 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_log_in);
当我在6小时前重新打开应用程序时,该按钮将再次启用。请帮忙
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_in);
Button mybutton=(Button)findViewById(R.id.buttonid);
final long currenttime= System.currentTimeMillis();
final SharedPreferences mysharedPreferences= getSharedPreferences("timeinfo", Context.MODE_PRIVATE);
final SharedPreferences.Editor editor=mysharedPreferences.edit();
final long secondtime=mysharedPreferences.getLong("writetime",currenttime);
mybutton.setOnClickListener(new View.OnClickListener()
{
public void onClick(final View v)
{
editor.putLong("writetime",currenttime);
v.setClickable(false);
if (currenttime-secondtime>300000)
{
v.setClickable(true);
}
else
{
v.setClickable(false);
}
}
});
按下按钮共享参考资料可以节省时间。 然后下次创建活动/片段时,读取值并将其减去当前时间。如果超过6小时,则启用按钮,否则禁用按钮。 缺点:如果设备是根设备,并且用户更改了保存的值,则会无限次单击按钮。您可以找到有关加密共享pref的信息,以便解决此问题,例如:
我会这样做(替换mybutton.setOnClickListener(…)部分)在您提供的代码示例的注释中,不要在onclicklistener中检查时间,而是在之前检查时间,并相应地启用/禁用按钮。之后,您可以添加您的侦听器,如果该按钮应被禁用,则该按钮将被禁用,侦听器代码将无法运行。我知道我在代码中犯了愚蠢的错误,但您能否重新安排我的代码并为我编写正确的代码,请。我想我已接近解决方案。您正在将时间值保存为毫秒,作为比较值(6小时)将是
“2160000”
。
myButton.setEnabled(false) // turn it off by default
if (currenttime-secondtime>=21600000) { // check if it can be enabled; 21600000ms is 6 hours
myButton.setEnabled(true); // wait time is up, enable button
editor.putLong("writetime", currenttime); // since we enabled the button right now, we save the current time
mybutton.setOnClickListener(new View.OnClickListener() { // user can click the button, add listener
public void onClick(final View v) {
// do whatever you want to do when the user can click the button
}
});
}