如何暂停/睡眠线程或进程中的Andr​​oid? [英] How to pause / sleep thread or process in Android?

查看:263
本文介绍了如何暂停/睡眠线程或进程中的Andr​​oid?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要打两行code之间的停顿,让我来解释一下:

I want to make a pause between two lines of code, Let me explain a bit:

- >用户点击一个按钮(其实是一个卡),我表现出来改变这个按钮的背景:

-> the user clicks a button (a card in fact) and I show it by changing the background of this button:

thisbutton.setBackgroundResource(R.drawable.icon);

- >让后说1秒,我需要变回它的背景回到按钮的previous状态:

-> after let's say 1 second, I need to go back to the previous state of the button by changing back its background:

thisbutton.setBackgroundResource(R.drawable.defaultcard);

- >我试过暂停与这两条线code之间的螺纹:

-> I've tried to pause the thread between these two lines of code with:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

不过,这是行不通的。也许这是我需要暂停过程中,而不是主题?

However, this does not work. Maybe it's the process and not the Thread that I need to pause?

我也试过(但它不工作):

I've also tried (but it doesn't work):

new Reminder(5);

通过这样的:

public class Reminder {

Timer timer;

        public Reminder(int seconds) {
            timer = new Timer();
            timer.schedule(new RemindTask(), seconds*1000);
        }

        class RemindTask extends TimerTask {
            public void run() {
                System.out.format("Time's up!%n");
                timer.cancel(); //Terminate the timer thread
            }
        }  
    }

我如何可以暂停/睡眠线程或进程?

How can I pause/sleep the thread or process?

推荐答案

一个很好的解决这个问题的方法是使用的处理器的postDelayed()方法:

A good solution to this problem is to use a Handler's postDelayed() method:

@Override
public void onClick(View v) {
    my_button.setBackgroundResource(R.drawable.icon);

    // Execute some code after 2 seconds have passed
    Handler handler = new Handler(); 
    handler.postDelayed(new Runnable() { 
         public void run() { 
              my_button.setBackgroundResource(R.drawable.defaultcard); 
         } 
    }, 2000); 
}

这篇关于如何暂停/睡眠线程或进程中的Andr​​oid?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆