Question

From an activity,I want to switch to another activity either by pressing a button or by waiting for some time (For example - 5 seconds). In the code below,if the user pressed the button within less than the specified timing (e.g: 5 seconds), he will be directed to a new activity. In case the user waited (5 seconds) without pressing any thing, the new activity will also be switched to.

The problem is, if the user pressed the button - before 5 seconds- to switch to the new activity, actually he will get what he wants, BUT after (5 seconds) the same activity will be launched again. How to invalidate the timer in case of the user chose to switch to the new activity by pressing the button.

Java Code:

introButton = (Button) findViewById(R.id.introButtonID);
    introButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent00 = new Intent(Intro.this, MPL.class);
            startActivity(intent00);
            finish();
        }
    });
...
...
new Handler().postDelayed(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            Intent intent01 =  new Intent(Intro.this, MPL.class);
            startActivity(intent01);
            finish();
        }
    }, SPLASH_TIME_OUT);
}
Was it helpful?

Solution

Try this code,

//Kept at class level
 private Runnable r;
 private Handler temp;


introButton = (Button) findViewById(R.id.introButtonID);
    introButton.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
           startActivity();
        }
    });

 r=new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
           startActivity();
        }
    };

 temp=new Handler();
temp.postDelayed(r, SPLASH_TIME_OUT);
}

private void startActivity(){
Intent intent00 = new Intent(Intro.this, MPL.class);
startActivity(intent00);
temp.removeCallbacks(r);
finish();
}

OTHER TIPS

I'm relative new to Android and I suggest to use something like this. There is no system-based way to do this functionality in a proper way.

I could only imagine to use system-time to implement this.

startInclTimer = starttime + seconds;
while(true){
    actualtime = System.currentTimeMillis();
    if (startInclTimer < actualtime) {
    //start intent
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top