如何在libGdx中设置多次展示插屏广告的时间间隔
Great question—this is a classic problem with in-memory state not surviving app lifecycle events. Right now, your timer lives in the app’s temporary memory, which gets wiped clean when the app closes or is terminated by the system. The fix is to save your accumulated play time to persistent storage that retains data even after the app restarts.
Here’s how to implement this across common game development platforms:
Unity
Unity’s built-in PlayerPrefs is perfect for simple key-value storage like this. You’ll want to:
- Load the saved time when the game starts
- Save the current accumulated time whenever the app closes or enters the background
- Reset the timer after showing an ad to start fresh for the next session
Example code:
private float totalPlayTime; private const string PlayTimeKey = "TotalPlayTime"; private const float AdThreshold = 250f; void Start() { // Load saved time on game start totalPlayTime = PlayerPrefs.GetFloat(PlayTimeKey, 0f); } void Update() { // Add time each frame (adjust for time scale if needed) totalPlayTime += Time.deltaTime; } void OnApplicationQuit() { // Save time when app closes PlayerPrefs.SetFloat(PlayTimeKey, totalPlayTime); PlayerPrefs.Save(); // Ensure changes are written immediately } void OnApplicationPause(bool isPaused) { if (isPaused) { // Save time when app is sent to background PlayerPrefs.SetFloat(PlayTimeKey, totalPlayTime); PlayerPrefs.Save(); } } public void adCheck() { if (totalPlayTime >= AdThreshold) { // Show interstitial ad here // Reset timer after ad is shown totalPlayTime = 0f; PlayerPrefs.SetFloat(PlayTimeKey, totalPlayTime); PlayerPrefs.Save(); } }
Android (Kotlin)
Use SharedPreferences to persist the timer value. Handle app lifecycle events to save and load data reliably:
class GameActivity : AppCompatActivity() { private var totalPlayTime: Long = 0 private val PLAY_TIME_KEY = "total_play_time" private val AD_THRESHOLD = 250000 // 250 seconds in milliseconds override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Load saved time from SharedPreferences val prefs = getSharedPreferences("GamePrefs", MODE_PRIVATE) totalPlayTime = prefs.getLong(PLAY_TIME_KEY, 0) } private fun updateTimer() { totalPlayTime += 1000 // Add 1 second every second // Save every 10 seconds to avoid frequent writes if (totalPlayTime % 10000 == 0) { savePlayTime() } } private fun savePlayTime() { val prefs = getSharedPreferences("GamePrefs", MODE_PRIVATE) prefs.edit().putLong(PLAY_TIME_KEY, totalPlayTime).apply() } override fun onPause() { super.onPause() savePlayTime() // Save when app is backgrounded } override fun onDestroy() { super.onDestroy() savePlayTime() // Save when app is closed } fun adCheck() { if (totalPlayTime >= AD_THRESHOLD) { // Show interstitial ad // Reset timer totalPlayTime = 0 savePlayTime() } } }
iOS (Swift)
Use UserDefaults for lightweight persistent storage. Handle app lifecycle events to preserve the timer:
class GameViewController: UIViewController { var totalPlayTime: TimeInterval = 0 let playTimeKey = "TotalPlayTime" let adThreshold: TimeInterval = 250 override func viewDidLoad() { super.viewDidLoad() // Load saved time totalPlayTime = UserDefaults.standard.double(forKey: playTimeKey) // Start updating the timer Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in self?.totalPlayTime += 1 // Save every 10 seconds if self?.totalPlayTime.truncatingRemainder(dividingBy: 10) == 0 { self?.savePlayTime() } } } func savePlayTime() { UserDefaults.standard.set(totalPlayTime, forKey: playTimeKey) UserDefaults.standard.synchronize() // Ensure immediate write } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) savePlayTime() // Save when view is hidden (app backgrounded) } func adCheck() { if totalPlayTime >= adThreshold { // Show interstitial ad // Reset timer totalPlayTime = 0 savePlayTime() } } }
Best Practices
- Avoid frequent writes: Saving to storage every second can cause performance overhead. Instead, save every 10-30 seconds or whenever the app is backgrounded/closed.
- Validate saved data: Add checks to handle corrupted values (e.g., default to 0 if the saved time is negative).
- Reset after ad: Always reset the timer once an ad is shown to prevent immediate repeat ads.
- Prioritize background saves: On mobile, the system can kill apps without warning, so saving in
onPause(Android) orviewWillDisappear(iOS) is more reliable than relying on app close events.
By implementing persistent storage for your timer, users will eventually hit the 250-second threshold even if they close and reopen the app multiple times.
内容的提问来源于stack exchange,提问作者Koby 27

