【问题标题】:How to implement a timeout on the button?如何在按钮上实现超时?
【发布时间】:2019-02-28 22:55:30
【问题描述】:

我想在按钮上放一个计时器之类的东西,也就是说,我有一个按钮,按下它后变为不活动状态,比如说2小时,两个小时后它可以再次点击,但是这样计时器就会一直计时即使应用程序已关闭或最小化。 我知道如何使按钮处于非活动状态有助于理解如何制作计时器。

我写了代码,当我按下按钮时,她会记下日期并停用按钮,然后她会得到新的日期并找出差异,当它是 10 秒时,她会激活再次按钮,但代码不起作用,请解释原因?

public class MainActivity extends AppCompatActivity {

Button button;
TextView textView;
private String TAG;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button = findViewById(R.id.button);
    textView = findViewById(R.id.textView);
    final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);




    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            button.setEnabled(false);
            SharedPreferences.Editor editor = preferences.edit();
            long startTime = System.currentTimeMillis();
            editor.putLong("Time", startTime);
            editor.apply();
            Log.d(TAG, "Time " + startTime);
        }
    });

    long startMillis = preferences.getLong("Time", 0);
    long now = System.currentTimeMillis();
    Log.d(TAG, "Now " + now);
    long difference = now - startMillis;

    if (difference == 10000) {
        button.setEnabled(true);
    }
    Log.i(TAG, "Time111: " + difference);

}

@Override
protected void onStart() {
    super.onStart();

}

}

【问题讨论】:

  • 请检查此question 可能会有所帮助

标签: android timer android-service onclicklistener android-button


【解决方案1】:

我只会保存上次点击的日期时间(例如在SharedPreference 中),每次活动/片段变为活动状态时,您都会检查该值并将其减去当前日期时间。

如果您的应用是公共应用,用户可以更改设备时钟,您可以配置BroadcastReceiver,该BroadcastReceiver 在每次时钟更改时触发并阻止您的应用或采取相应的操作。

如果此按钮在您自己的某些 API 中触发和操作,则处理它的最佳方法是在您的服务器中记录最后一次。请记住,我们在客户端应用程序中的许多方面都受到限制。

【讨论】:

  • 我按照你说的做了,但是没有用,请告诉我出了什么问题(问题已编辑)
  • @AraGevorgyan 问题是你的条件difference == 10000 它几乎永远不会得到满足。试试difference >= 10000。
  • 是的,我也注意到一个愚蠢的错误)但现在我不明白如何确保按下按钮后她每秒检查一次时差
  • 解决问题的方法有很多种,我不知道哪一种最能满足您的要求。有几个想法是启动一个每 2 秒循环一次的线程,另一个想法是配置一个闹钟来唤醒您的应用并更改按钮状态。
【解决方案2】:

您可以从 API 中查看当前时间,并在单击按钮时将其保存在首选项中,并据此启用/禁用按钮。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-01
    • 2014-12-07
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多