简体   繁体   English

Android在Handler / runnable中启动新的Activity确实很慢

[英]Android-Starting new Activity in Handler/runnable is really slow

I am making an android app that requires a runnable. 我正在制作需要可运行的android应用。 I am starting a new activity from the runnable. 我正在从runnable开始一项新活动。 The new activity comes up and works fine. 出现了新活动,并且效果很好。 The issue is that when the call is made to start the activity, it is incredibly slow. 问题是,当调用开始活动时,它的速度非常慢。 It takes a full 5 seconds to start the activity when I want it to be instantaneous. 当我希望它是瞬时的时,要花整整5秒钟才能开始该活动。

Boolean handlerrun=true;
Intent intent= new Intent(this,newactivity.class);
int somevalue=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
            setContentView(R.layout.gameactivity);


handler=new Handler();

final Runnable r = new Runnable()
{

    public void run() 
    {
if(handlerrun){somevalue++;}

if(somevalue>500){
handlerrun=false;
startActivity(intent);
finish();
        }



        handler.postDelayed(this, 1);}


}
}; 

handler.postDelayed(r, 1);

}

The activity starts when somevalue is greater than 500. To stop the handler from increasing the value of somevalue, I use a boolean handlerrun, which only runs the handler when it is true. 该活动在somevalue大于500时开始。为了阻止处理程序增加somevalue的值,我使用了布尔处理程序运行,仅当处理程序为true时才运行该处理程序。 When somevalue is greater than 500, handlerrun= false so the handler doesn't increase the value. 当somevalue大于500时,handlerrun = false,因此处理程序不会增加该值。 I tried using the handler.removeCallbacksandMessages() method but it didn't work. 我尝试使用handler.removeCallbacksandMessages()方法,但是没有用。 Logcat doesn't give me any errors.Any help would be appreciated. Logcat不会给我任何错误。任何帮助将不胜感激。

You could try something like this: 您可以尝试这样的事情:

@Override
protected void onResume() {
    super.onResume();

    if(done){
        return;
    }
    done = true;
    final Handler handler = new Handler();
    handler.postDelayed(new Runnable() {

        @Override
        public void run() {
            startActivity(new Intent(getApplicationContext(), YourActivity.class));
            finish();
            overridePendingTransition(0, 0);
        }
    }, 5000);
}

That will start YourActivity after 5 seconds approximately. 这将在大约5秒钟后启动YourActivity

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM