Android等待1分钟而不停止线程

时间:2016-04-21 13:12:44

标签: java android multithreading

如何在不停止线程的情况下在Android应用程序中等待一分钟?我需要每分钟为X轮播放一个声音。除了等待代码之外,我所有代码都在工作。

public void startRounds(View v)
{
    MediaPlayer mp = MediaPlayer.create(this, R.raw.ding);
    mp.start();

    EditText txtRounds = (EditText) findViewById(R.id.txtRounds);
    rounds = Integer.parseInt(txtRounds.getText().toString());

    oneSession();
}

private void oneSession()
{
    //this needs to be replaced with my new wait one minute function
    SystemClock.sleep(60000);

    MediaPlayer mp2 = MediaPlayer.create(this, R.raw.ding);
    mp2.start();

    if (rounds != 1) {
        rounds--;
        oneSession();
    }
}

解决:

new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                  //do something
            }
        }, 60 * 1000);

3 个答案:

答案 0 :(得分:2)

我不确定这是否是您真正想要的,但do something

之后会60 * 1 seconds
 new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                      //do something
                }
            }, 60 * 1000);

答案 1 :(得分:0)

你可以使用Handler来执行而不会阻塞thread.eg

handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                /**put your code inside this
                 * this method will get exceuted after 1 min without stopping thread
                 * same thing can be recursive based on your requirement*/

            }
        },60000);

答案 2 :(得分:0)

在另一个线程中运行分钟,因为在UI上线程de声音将停止:

new Thread(new Runnable() {
                @Override
                public void run() {
                    try{
                        Thread.sleep(60000)
                    }catch(InterruptedExcpetion e){

                    }
            }).start();