如何在Android上暂停/延迟?

时间:2012-06-17 01:26:49

标签: java android

我目前正在学习如何为Android移动设备开发应用程序。

我写了一个测试应用程序,在设备屏幕上显示数字0-9。我创建了一个简单的函数来延迟数字的变化。

但是,在运行应用程序时,仅显示最终编号。在最终数字显示之前还有一段延迟。我假设暂停的长度是我定义的延迟乘以要显示的位数。

如何创建一个可以延迟更改数字的应用程序?

public class AndroidProjectActivity extends Activity {
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        Main();
    }

void Delay(int Seconds){
    long Time = 0;
    Time = System.currentTimeMillis();
    while(System.currentTimeMillis() < Time+(Seconds*1000));
}

void Main() {
    String ConvertedInt;
    TextView tv = new TextView(this);
    setContentView(tv);

    for(int NewInt = 0; NewInt!= 9; NewInt++){
        ConvertedInt = Character.toString((char)(NewInt+48));
        tv.setText(ConvertedInt);
        Delay(5);
    }
}

3 个答案:

答案 0 :(得分:1)

尝试创建threadwhich sleeps for certain interval of time,然后将值增加1到9.并使用Handler to update the UI

您也可以使用AsyncTask

答案 1 :(得分:1)

这样做的一种方法是创建一个可以更新视图的runnable。这仍将在UI线程上更新,但在后台等待。下面的代码中可能存在错误,但它应该在稍微调整的情况下运行..

阻止任何系统调用进入您的活动并不好,因为您正在阻止UI线程。您的应用将被强制关闭,并显示“应用无响应”消息。这是另一个好example

public class AndroidProjectActivity extends Activity {
    private Handler mHandler;
    private TextView mTextView;
    private Runnable mCountUpdater = new Runnable() {
        private int mCount = 0;
        run() {
           if(mCount > 9)
               return;
           mTextView.setText(String.valueOF(mCount+48));
           mCount++;
           // Reschedule ourselves.
           mHandler.postDelayed(this, 5000);
        }
    }
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        // Cleaner to load a view from a layout..
        TextView tv = new TextView(this);
        setContentView(tv);
        mTextView = tv;
        // Create handler on UI thread.
        mHandler = new Handler();
        mHandler.post(mCountUpdater);
    }
}

答案 2 :(得分:0)

对main()的调用阻止了UI,因此在调用完成之前它无法显示任何数字。

相关问题