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

使用Timer调度仍触发CalledFromWrongThreadException异常求助

解决android.view.ViewRootImpl$CalledFromWrongThreadException异常

你的代码核心问题是:虽然把Timer的创建逻辑放到了runOnUiThread中,但TimerTask的run()方法是在后台线程执行的,调用SparrowAnimation()时依然是在非UI线程操作View,所以还是会触发这个异常。

修正方案一:在TimerTask内部切换到UI线程

直接在TimerTask的run()方法里,将View操作逻辑切换回UI线程:

private void SparrowTimer() {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
        @Override
        public void run() {
            // 切换到UI线程执行View动画操作
            runOnUiThread(() -> SparrowAnimation());
        }
    }, 0, 6000); // 延迟0ms执行,每6秒循环一次
}

private void SparrowAnimation() {
    sparrowFlyingImage.startAnimation(animationSparrow);
}

修正方案二:使用Handler实现循环(更推荐)

Android中更推荐用Handler来实现UI线程的定时循环,避免Timer可能带来的内存泄漏问题:

private Handler uiHandler = new Handler(Looper.getMainLooper());
private Runnable sparrowLoopRunnable = new Runnable() {
    @Override
    public void run() {
        SparrowAnimation();
        // 6秒后再次执行当前Runnable,实现循环
        uiHandler.postDelayed(this, 6000);
    }
};

private void SparrowTimer() {
    // 启动循环
    uiHandler.post(sparrowLoopRunnable);
}

// 记得在页面销毁时停止循环,防止内存泄漏
@Override
protected void onDestroy() {
    super.onDestroy();
    uiHandler.removeCallbacks(sparrowLoopRunnable);
}

private void SparrowAnimation() {
    sparrowFlyingImage.startAnimation(animationSparrow);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:55:16