You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用关闭时如何存储计数器最后值并重启后恢复

How to Add Persistence to Your Simple Counter App

Hey there! Let's fix that persistence gap for your counter app—it's a common need and totally straightforward to implement. The core idea is to save the counter's value to a persistent storage system whenever it changes, then load that value back when the app starts up. Here's how to do it for the most common platforms:

For Web Apps (Browser-Based)

The easiest way here is to use the browser's built-in localStorage—it's a simple key-value store that persists even after the browser is closed.

Step 1: HTML Structure (Example)

<div class="counter-container">
  <h2>Counter</h2>
  <p id="counter-display">0</p>
  <div class="button-group">
    <button id="decrease-btn">-</button>
    <button id="increase-btn">+</button>
    <button id="clear-btn">Clear</button>
  </div>
</div>

Step 2: JavaScript Logic with Persistence

// Initialize counter: load saved value from localStorage, default to 0 if none exists
let counterValue = parseInt(localStorage.getItem('savedCounter')) || 0;
const displayElement = document.getElementById('counter-display');

// Helper function to update display AND save the new value
function updateCounter() {
  displayElement.textContent = counterValue;
  localStorage.setItem('savedCounter', counterValue.toString());
}

// Load the saved value on page load
updateCounter();

// Attach click handlers to buttons
document.getElementById('increase-btn').addEventListener('click', () => {
  counterValue++;
  updateCounter();
});

document.getElementById('decrease-btn').addEventListener('click', () => {
  counterValue--;
  updateCounter();
});

document.getElementById('clear-btn').addEventListener('click', () => {
  counterValue = 0;
  updateCounter();
});

How It Works

  • localStorage.getItem('savedCounter') pulls the last saved value when the app starts. If it's the first run, this returns null, so we use || 0 to default to 0.
  • Every time the counter changes (via +, -, or Clear), updateCounter() updates the display and saves the new value to localStorage as a string (since localStorage only stores strings).

For Mobile Apps

Android (Kotlin Example)

Use SharedPreferences, Android's built-in lightweight storage for small key-value data:

class MainActivity : AppCompatActivity() {
    private lateinit var sharedPref: SharedPreferences
    private var counterValue = 0
    private lateinit var displayTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // Initialize SharedPreferences
        sharedPref = getSharedPreferences("CounterStorage", Context.MODE_PRIVATE)
        // Load saved value, default to 0
        counterValue = sharedPref.getInt("counterValue", 0)
        displayTextView = findViewById(R.id.counter_display)
        updateDisplay()

        // Button click handlers
        findViewById<Button>(R.id.increase_btn).setOnClickListener {
            counterValue++
            updateDisplay()
            saveCounter()
        }

        findViewById<Button>(R.id.decrease_btn).setOnClickListener {
            counterValue--
            updateDisplay()
            saveCounter()
        }

        findViewById<Button>(R.id.clear_btn).setOnClickListener {
            counterValue = 0
            updateDisplay()
            saveCounter()
        }
    }

    private fun updateDisplay() {
        displayTextView.text = counterValue.toString()
    }

    private fun saveCounter() {
        with(sharedPref.edit()) {
            putInt("counterValue", counterValue)
            apply() // Async save (use commit() for sync if needed)
        }
    }
}

iOS (Swift Example)

Use UserDefaults, Apple's equivalent for small persistent data:

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var counterDisplay: UILabel!
    private var counterValue = 0
    private let defaults = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()
        // Load saved value, default to 0
        counterValue = defaults.integer(forKey: "savedCounter")
        updateDisplay()
    }

    private func updateDisplay() {
        counterDisplay.text = "\(counterValue)"
    }

    private func saveCounter() {
        defaults.set(counterValue, forKey: "savedCounter")
    }

    @IBAction func increaseTapped(_ sender: UIButton) {
        counterValue += 1
        updateDisplay()
        saveCounter()
    }

    @IBAction func decreaseTapped(_ sender: UIButton) {
        counterValue -= 1
        updateDisplay()
        saveCounter()
    }

    @IBAction func clearTapped(_ sender: UIButton) {
        counterValue = 0
        updateDisplay()
        saveCounter()
    }
}

Key Takeaway

No matter which platform you're building for, the pattern is the same:

  • Load on startup: Fetch the saved value from persistent storage when the app initializes.
  • Save on change: Every time the counter's value updates (via any button click), immediately save the new value to storage.

This ensures your counter picks up right where it left off, even after the app is closed and restarted.

内容的提问来源于stack exchange,提问作者hassanrazadev

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:50:56