我是Android编程新手。 我正在使用Handler来更改图像,但它应该只发生30秒,之后我想调用另一个活动
我的代码:
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);
如何在30秒后停止此活动并拨打其他活动? 请帮忙
答案 0 :(得分:1)
您可以使用计时器尝试此操作..下面的代码将每1秒运行一次代码,直到达到30秒
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);
}
});
答案 1 :(得分:1)
1)延迟以毫秒为单位,如果您想每秒更改图像handler.postDelayed(this,100);
应更改为handler.postDelayed(this,1000);
(1s = 1000ms)
2)停止任务:
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
}
}
};
或者您可以安排第二次运行以在30秒后停止更改图像并开始另一项活动:
handler.postDelayed(new Runnable() {
@Override
public void run() {
handler.removeCallbacks(runnable); //stop next runnable execution
//TODO start second activity
}
}, 30000);