Justaprogrammer
Justaprogrammer

Reputation: 11

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

I am making an android app that requires a runnable. I am starting a new activity from the 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.

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. When somevalue is greater than 500, handlerrun= false so the handler doesn't increase the value. I tried using the handler.removeCallbacksandMessages() method but it didn't work. Logcat doesn't give me any errors.Any help would be appreciated.

Upvotes: 0

Views: 3489

Answers (1)

Junior Buckeridge
Junior Buckeridge

Reputation: 2085

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.

Hope it helps.

Upvotes: 1

Related Questions