【问题标题】:Displaying new screen takes too much time! (threads maybe...?)显示新屏幕需要太多时间! (线程可能......?)
【发布时间】:2016-03-21 05:40:43
【问题描述】:

TL;DR:我的意图是从另一个线程开始花费太多时间,而从主线程开始非常快。我实际上不知道这是线程问题还是onFinish 方法的问题

所以,我有一个倒计时。从二十秒开始倒计时,onFinish()我有一个意图。我还定期根据millisUntilFinished 设置我的textView 的文本。 我注意到,在 textView 显示 1 second left 之后,意图在 3 秒后开始。

但是,如果我使用 onFinish 方法的外部的意图来切换活动,则下一个活动会很快开始。所以,

为什么从onFinish 方法启动一个意图比平时花费更长的时间?

根据我对计时器的小测试,我决定我需要一种更好更快的方法来启动我的意图,因为很明显,onFinish 方法在更多时间后启动,然后计时器实际启动。那么,我应该怎么做才能更快地开始我的意图呢?我需要它立即...

 public void startTimer() {

        timer = new CountDownTimer(20000, 1000) {

            public void onTick(long millisUntilFinished) {

                int seconds = (int) millisUntilFinished/1000;

                timetext.setText(seconds + ":00");

            }

            public void onFinish() {



                Intent intent = new Intent(MainActivity.this, GameOver.class);
                intent.putExtra("score", score);  // pass your values and retrieve them in the other Activity using keyName
                intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
                startActivity(intent);

            }
        }.start();

    }

谢谢,

鲁基尔

【问题讨论】:

  • 尝试使用 MainActivity.this.startActivity(intent);或尝试使用 runOnUiThread

标签: java android multithreading performance android-intent


【解决方案1】:

尝试将startActivity(intent) 放在计时器之外:

    public void startTimer() {

    timer = new CountDownTimer(20000, 1000) {

        public void onTick(long millisUntilFinished) {

            int seconds = (int) millisUntilFinished/1000;

            timetext.setText(seconds + ":00");

        }

        public void onFinish() {



            Intent intent = new Intent(MainActivity.this, GameOver.class);
            intent.putExtra("score", score);  // pass your values and retrieve them in the other Activity using keyName
            intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");


        }
    }.start();

    startActivity(intent);
}

【讨论】:

  • 然后,onFinish 方法将用于该类。我们会覆盖错误的东西,对吧?
  • onFinish 方法在CountDownTimer 内部使用,并在计时器完成所有滴答时被调用。
  • 对不起,我的答案弄错了,您的onFinish 方法在正确的位置,但请尝试将startActivity(intent) 放在柜台外面。
  • 您需要声明Intent 以及计时器之外的所有内容。对不起,但我正在尽可能多地环顾四周,以便为您找到正确的答案!让我知道会发生什么
【解决方案2】:

你可以试试:

public void onFinish() {
        cancel(); //Cancel the countdown

        Intent intent = new Intent(MainActivity.this, GameOver.class);
        intent.putExtra("score", score);  // pass your values and retrieve them in the other Activity using keyName
        intent.putExtra("classname", "com.example.ruchir.swapproperties.MainActivity");
        startActivity(intent);

    }

`

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-20
    • 2019-07-04
    • 2014-11-24
    • 2014-02-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多