简体   繁体   English

android 应用程序在计时器循环时崩溃

[英]android app crashes while timer loop

I'm new here and noob as well.我是新来的,也是菜鸟。 I started learning Java and Android by making my first simple app.我通过制作第一个简单的应用程序开始学习 Java 和 Android。

I want to do the time loop to do some function every 1 sec.我想做一个时间循环,每 1 秒做一些功能。
I have this:我有这个:

new Timer().scheduleAtFixedRate(new TimerTask(){
    @Override
    public void run(){
        imV.setImageResource(stageArray.getResourceId(step, -1));
        Log.d("MyApp","I am here");
        step ++;
    }
},0,1000);

It's in my init() function.它在我的init()函数中。
After I run this on my device, the app crashes.在我的设备上运行此程序后,应用程序崩溃。
When I delete the imV.setImageRes... line it runs, but I don't get log notifications.当我删除imV.setImageRes...行时,它会运行,但我没有收到日志通知。
The step value is changing.步长值正在改变。
Something similiar is happening when I use a Handler.当我使用处理程序时,发生了类似的事情。

So why my app crash?那么为什么我的应用程序崩溃?
Why cannot I see any log.d from this loop?为什么我看不到此循环中的任何 log.d?
Are there better ways to do time loop to make simple changes?有没有更好的方法来做时间循环来进行简单的更改?

Your app has crashed because you access the Android UI toolkit from outside the UI thread when you call imV.setImageResource(stageArray.getResourceId(step, -1));您的应用程序崩溃了,因为您在调用imV.setImageResource(stageArray.getResourceId(step, -1));从 UI 线程外部访问了 Android UI 工具包 . . So that, exception has occurred.所以,异常发生了。 You must set image for imageview in UI thread:您必须在 UI 线程中为 imageview 设置图像:

runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    imV.setImageResource(stageArray.getResourceId(step, -1));
                }
            });

Or simple solution with CountDownTimer或使用CountDownTimer 的简单解决方案

new CountDownTimer(totalStep * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
            step = millisUntilFinished/1000;
            imV.setImageResource(_yourResID);
        }

        @Override
        public void onFinish() {
            Log.d("Finish", "Done");
        }
    }.start();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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