执行一个方法只有一天一次的Android Java

huangapple go评论68阅读模式
英文:

Executing a method only once a day android java

问题

我想让这些密钥每天只上传一次。我该如何做到这一点?

英文:
public ListenableFuture<?> fakeUpload() {
    ImmutableList.Builder<Keys> builder = ImmutableList.builder();
    for (int i = 0; i < 14; i++) {
      byte[] bytes = new byte[KEY_SIZE_BYTES];
      RAND.nextBytes(bytes);
      builder.add(
          Keys.newBuilder()
              .setKeyBytes(bytes)
              .setIntervalNumber(FAKE_INTERVAL_NUM)
              .build());

    }

    return doUpload(builder.build(), true);
  }

I want to make these keys upload only once a day.
How can i do that?

答案1

得分: 3

现在您可以在应用程序活动中编写此代码,您可以选择创建一个服务并在其中编写代码:

private fun shouldUploadFakeKeys(): Boolean {
    if (sharedPreferenceUtil.getInt(Constants.EXTRA_DAILY_KEYS_UPLOAD) != getTodaysDate()) {
        sharedPreferenceUtil.putBoolean(Constants.EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY, false)
        return true
    } else if (sharedPreferenceUtil.getBoolean(Constants.EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY)) {
        return false
    }
    return true
}

fun getTodaysDate(): Int {
    return ZonedDateTime.now().dayOfMonth
}

如果您还没有常量文件,请创建一个:

Constants.kt

class Constants {
    companion object {
        const val EXTRA_DAILY_KEYS_UPLOAD = "EXTRA_DAILY_KEYS_UPLOAD"
        const val EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY = "EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY"
    }
}
英文:

Now you can write this code in application activity where you want to or create a service and write the code there :-

private fun shouldUploadFakeKeys(): Boolean {
    if (sharedPreferenceUtil.getInt(Constants.EXTRA_DAILY_KEYS_UPLOAD) != getTodaysDate()) {
        sharedPreferenceUtil.putBoolean(Contants.EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY,false)
        return true
    } else if (sharedPreferenceUtil.getBoolean(Contants.EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY)) {
        return false
    }
    return true
}
fun getTodaysDate(): Int {
        return ZonedDateTime.now().dayOfMonth
    }

Create a constants file if you don't have one already:-

Constants.kt

class Constants{
    companionObject{
         const val EXTRA_DAILY_KEYS_UPLOAD = "EXTRA_DAILY_KEYS_UPLOAD"
         const val EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY = "EXTRA_HAS_FAKE_KEYS_UPLOADED_TODAY"
    }
}

huangapple
  • 本文由 发表于 2020年8月4日 13:44:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/63240887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定