Reputation: 31
I am new to android programming. I am using Handler to change images but it should happen only for 30 sec and after that i want to call another activity
My code:
imageView = (ImageView) findViewById(R.id.imageView);
final int[] imageArray = {R.drawable.a, R.drawable.b, R.drawable.c, R.drawable.d};
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i = 0;
@Override
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1){
i= 0;
}
handler.postDelayed(this,100);
}
};
handler.postDelayed(runnable, 3000);
How do I stop this activity and call another activity after 30 sec? Please help
Upvotes: 0
Views: 2359
Reputation: 9117
You can try this by using Timer.. below code will run the code every 1 second until reach 30 seconds
this.runOnUiThread(new Runnable() {
@Override
public void run() {
int globalTimer = 0;
// 30 times 30 * 1000 = 30000 == 30 seconds
int limitTimer = 30;
int i = 0;
// create Timer
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
globalTimer++;
//run your code
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1){
i= 0;
}
//check if globalTimer is equal to limitTimer
if (globalTimer == limitTimer) {
timer.cancel(); // cancel the Timer
// jump to another activity
Intent intent = new Intent(Class.this,Name.class);
startActivity(intent);
}
}
}, 0, 1000);
}
});
Upvotes: 1
Reputation: 86
1) delay is in milliseconds, if you want to change image every second handler.postDelayed(this,100);
should be changed to handler.postDelayed(this,1000);
(1s = 1000ms)
2) stop task:
long startTime = System.currentTimeMillis();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
int i = 0;
@Override
public void run() {
imageView.setImageResource(imageArray[i]);
i++;
if(i>imageArray.length-1){
i= 0;
}
if (System.currentTimeMillis() - startTime < 30000){
handler.postDelayed(this,1000);
} else {
//TODO start second activity
}
}
};
or you can schedule second runnable to stop changing images after 30s and start another activity:
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.removeCallbacks(runnable); //stop next runnable execution
//TODO start second activity
}
}, 30000);
Upvotes: 1