简体   繁体   中英

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?

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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM