我想在上传 Firebase 照片后禁用上传按钮一天。我尝试了这些代码,当我更改 Activity 时倒计时工作不正确。
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long currentTime = new Date().getTime();
SharedPreferences.Editor editor = prefs.edit();
editor.putLong("time", currentTime);
editor.apply();
dwn.setEnabled(false);
SharedPreferences prefs = getSharedPreferences("time", Context.MODE_PRIVATE);
long previousTime = prefs.getLong("time", 0);
long currentTime = new Date().getTime();
if (currentTime - previousTime > 60*1000){
dwn.setEnabled(true);
} else {
dwn.setEnabled(false);
new CountDownTimer(currentTime - previousTime, 1000) {
public void onTick(long millisUntilFinished) {
dwn.setText("fdfjhsn" + millisUntilFinished / 1000);
}
public void onFinish() {
dwn.setEnabled(true);
}
}.start();
最佳答案
这可能比您想要的更多,但我会将决策提取到一个单独的类中。考虑以下因素:
interface UserUploadHelper {
void userUploadedImage();
boolean canUserUploadImages();
}
我们可以在 SharedPreferences 的支持下实现它。然后可以将该对象注入(inject)到我们需要的任何地方:
class SharedPreferencesUserUploadHelper implements UserUploadHelper {
private static final String LAST_IMAGE_UPLOAD_TIME = "last.user.upload.time";
private static final String PREFS_NAME = "user.upload";
private static final String PREFS_MODE = Context.MODE_PRIVATE;
private static final String MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
private final SharedPreferences sharedPreferences;
SharedPreferencesUserUploadHelper(Context context) {
sharedPreferences = context.getSharedPreferences(PREFS_NAME, PREFS_MODE);
}
@Override
void userUploadedImage() {
sharedPreferences.edit().putLong(
LAST_IMAGE_UPLOAD_TIME,
new Date().getTime()
).apply();
}
@Override
boolean canUserUploadImages() {
long lastUploadTime = sharedPreferences.getLong(LAST_IMAGE_UPLOAD_TIME, 0L);
long now = new Date().getTime();
return lastUploatTime - now > MILLIS_IN_DAY;
}
}
在上传代码中,当代码完成上传时,您可以调用userUploadedImage()
在您的 Activity 代码中,您可以使用 canUserUploadImages()
检查是否应启用该按钮。
这样做可以让您更改存储该值并计算超时的方式,而无需更改您的 Firebase 逻辑或 View 逻辑。
您可以使用 Dagger 之类的工具将其注入(inject)到类中,或者只需通过其构造函数创建它的实例即可。如果您想隐藏具体的 SharedPreferencesUserUploadHelper 实现,您可以使用工厂!当您稍后可能决定更改此类的实现方式时,这很好。
public UserUploadHelperFactory {
public UserUploadHelper create(Context context) {
return new SharedPreferencesUploadHelper();
}
}
如果我们想更进一步,我们实际上会将原来的接口(interface)分成两个不同的接口(interface),每个方法一个,因为每个方法都有不同的利益相关方,并且,例如, View 不应该能够调用userUploadedImage
(这使得原始接口(interface)稍微违反了接口(interface)隔离原则!)
关于java - 如何禁用按钮一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57133911/