Android中每5秒更新WebView问题:代码仅首次执行后停止
Hey there! I see you're having trouble getting your WebView to refresh every 5 seconds—right now it only runs once and stops. Let's sort this out with a couple of reliable approaches that'll keep that refresh cycle going steady.
Why your current code only runs once
Chances are, you used a one-off postDelayed call or a TimerTask that didn't re-schedule itself. For repeated execution, we need to make sure the task tells the system to run it again after each completion.
Approach 1: Handler + Runnable (Java/Kotlin)
This is the classic Android way to handle repeated UI-thread tasks. The key is to have the Runnable re-post itself after it executes.
Java Example:
// Initialize Handler and Runnable private Handler refreshHandler = new Handler(Looper.getMainLooper()); private Runnable refreshRunnable = new Runnable() { @Override public void run() { // Update your WebView here—reload the URL or inject JS, whatever you need if (webView != null && !webView.isDestroyed()) { webView.reload(); } // Schedule the next run 5 seconds later refreshHandler.postDelayed(this, 5000); } }; // Start the refresh cycle when the activity is active @Override protected void onResume() { super.onResume(); // Start the first run after 5 seconds (or pass 0 to run immediately then repeat) refreshHandler.postDelayed(refreshRunnable, 5000); } // Stop the cycle when the activity is paused to avoid memory leaks @Override protected void onPause() { super.onPause(); refreshHandler.removeCallbacks(refreshRunnable); }
Kotlin Example:
private val refreshHandler = Handler(Looper.getMainLooper()) private val refreshRunnable = Runnable { webView?.takeIf { !it.isDestroyed() }?.reload() refreshHandler.postDelayed(this, 5000) } override fun onResume() { super.onResume() refreshHandler.postDelayed(refreshRunnable, 5000) } override fun onPause() { super.onPause() refreshHandler.removeCallbacks(refreshRunnable) }
Pro Tip: Always use Looper.getMainLooper() to make sure the Handler runs on the UI thread—WebView operations must happen on the main thread! Also, checking if the WebView isn't destroyed prevents crashes if the activity is torn down.
Approach 2: Kotlin Coroutines (Modern & Clean)
If you're using Kotlin, coroutines make this even simpler, especially with lifecycle-aware scopes to avoid leaks automatically.
import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch private var refreshJob: Job? = null override fun onResume() { super.onResume() refreshJob = lifecycleScope.launch { // Keep running as long as the lifecycle is active while (isActive) { delay(5000) webView?.takeIf { !it.isDestroyed() }?.reload() } } } override fun onPause() { super.onPause() // Cancel the job to stop the refresh cycle refreshJob?.cancel() }
This uses lifecycleScope, which is tied to your activity/fragment's lifecycle—so if the lifecycle is destroyed, the coroutine cancels itself automatically. No need to worry about forgetting to clean up!
What to avoid
- Don't use a raw
TimerandTimerTaskunless you handle threading properly—they run on a background thread, and you'll need to post WebView operations back to the main thread, which adds unnecessary complexity. - Never forget to stop the refresh cycle when your activity/fragment is paused/destroyed—this prevents memory leaks and unnecessary network calls when the app isn't visible.
Pick the approach that fits your codebase, and you'll have that WebView refreshing every 5 seconds like a charm!
内容的提问来源于stack exchange,提问作者keithschm

