首页 文章

如果我想要一个意图到其他类的计时器,我应该输入什么代码?

提问于
浏览
1

如果我想要一个具有定时器的类可以放在其他类中,我应该放什么代码?但它有一个按钮,如果我点击按钮,它将自动意图到其他类 . 它就像一个游戏,如果你没有点击按钮,你将被转移到另一个类,因为它有一个时间限制的例子是:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.easyone);
        a = (ImageButton) findViewById(R.id.ib_a);
        b = (ImageButton) findViewById(R.id.ib_b);
        c = (ImageButton) findViewById(R.id.ib_c);
        a.setOnClickListener(new View.OnClickListener() {

            @Override   
               public void onClick(View v) {
                    Toast.makeText(getApplicationContext(),"CORRECT!",
                            Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent(getApplicationContext(),EasyTwo.class);
                    startActivity(intent);
            }
        });
    }

    Thread timer = new Thread(){

        protected void timeout() {
    try {
        sleep(5000);

        }catch(InterruptedException e){
            e.printStackTrace();

            Intent intent = new Intent(getApplicationContext(),TimesUp.class);
            startActivity(intent);
        }
    }
};start();

    }
}//this one

我不知道我应该输入什么代码所以我把睡眠虽然我知道它是错误的

我在最后一个括号上有一个错误我在括号中非常菜鸟你能帮助我吗?

3 回答

  • 0

    您可以像这样使用超时:

    private void timeout() {
    
        new Handler().postDelayed(new Runnable() {
    
            @Override
            public void run() {
     Intent intent = new Intent(getApplicationContext(),MainMenu.class);
                startActivity(intent);
    
    }
        }
        }, 5000);
    

    我一直使用这种方法,我从来没有遇到任何问题 .

  • 2

    根据我的理解,你想要做的是如果点击 Button 或者时间到了,你想要去下一个 Activity .

    如果你不点击按钮,你将转移到另一个类,因为它有一个时间限制

    使用您的代码,如果未单击 ButtonThread 将无法运行,因此您需要将该代码移动到 Listener 之外,以便在未单击 Button 时运行它,无论您希望它在何处启动 .

    所以我把睡眠虽然我知道这是错误的

    sleep() 没关系,因为它在背景上 Thread

  • 1

    使用此参考

    private void timeOutCheck() {
        new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //call intent here
                    }
                }, 5 * 1000);
    }
    

相关问题