java - Activity 结束后停止 Handler Runnable

标签 java android multithreading runnable

我有一个方法可以让 TextView 充当“正在加载...”指示器。

我正在使用每 .5 秒更新一次 TextView 的 Runnable 来执行此操作。这是我的功能:

public void displayFlash() {
    animate = true;
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            while(animate) {
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                handler.post(new Runnable() {
                    public void run() {
                        System.out.println("Running");
                        numFrames++;
                        switch (numFrames % 3) {
                        case 0:
                            loading.setText("Loading.");
                            break;
                        case 1:
                            loading.setText("Loading..");
                            break;
                        case 2:
                            loading.setText("Loading...");
                            break;

                        }
                    }
                });
            }
    }
    };
    new Thread(runnable).start();
}

问题是,在这个 Activity 完成(并销毁)之后,线程继续运行。我在 Runnable 中有一个 System.out.println("running"); 并在此 Activity 完成后继续记录。我需要做什么才能杀死它?我已经尝试过 handler.removeCallbacks(runnable);Thread.interrupt(); 但没有成功。

最佳答案

public void displayFlash() {
    animate = true;
    final Handler handler = new Handler();
    Runnable yourRunnable = new Runnable() {
        @Override
        public void run() {
            System.out.println("Running");
            numFrames++;
            switch (numFrames % 3) {
                case 0:
                    loading.setText("Loading.");
                    break;
                case 1:
                    loading.setText("Loading..");
                    break;
                case 2:
                    loading.setText("Loading...");
                    break;
            }
            handler.postDelayed(this, 500);
        }
    }
    handler.post(yourRunnable);
}

完成后,调用 handler.removeCallbacks(yourRunnable);

关于java - Activity 结束后停止 Handler Runnable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31844281/

相关文章:

java : The import collides with another import statement

java - 为什么不在 StringUtils、Spring-Core 中使用 len 而不是 str.length() ?

java - 添加、删除、更新数据时如何刷新 JTable

java - Autowiring 子类但使用父类作为引用

java - 用户自定义布局的更简单方法

android - 触发系统音量条

java - 从android中的类获取静态值

multithreading - 多线程对 IO-bound 操作有意义吗?

java - 使用二进制信号量

c++ - 多线程导致分段违规