我正在尝试启动一项新活动“SMS.java”,如果我在30秒内不响应我的计时器。 30秒后,应该开始新的活动。谁能帮我吗???第5行的类Timer扩展了CountDownTimer .. 这是代码:
//TimerAct.java
public class TimerAct extends Activity
{
static TextView timeDisplay;
Timer t;
int length = 30000;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.time);
timeDisplay = (TextView) findViewById(R.id.timer);
timeDisplay.setText("Time left: " + length / 1000);
t = new Timer(length, 1000);
t.start();
View b1 = findViewById(R.id.abort);
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
t.cancel();
finish();
}
});
}
}
//Timer.java
public class Timer extends CountDownTimer
{
public Timer(long millisInFuture, long countDownInterval)
{
super(millisInFuture, countDownInterval);
}
public void onTick(long millisUntilFinished)
{
TimerAct.timeDisplay.setText("Time left: " + millisUntilFinished / 1000);
}
public void onFinish()
{
TimerAct.timeDisplay.setText("Time over!!!");
}
}
答案 0 :(得分:0)
对于计时器方法,您可以更好地使用线程。它会工作。 这是使用线程在Android中显示计时器的示例。它每秒运行一次线程。如果你想改变时间。
Timer MyTimer=new Timer();
MyTimer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
TimerBtn=(Button) findViewById(R.id.Timer);
TimerBtn.setText(new Date().toString());
}
});
}
}, 0, 1000);
答案 1 :(得分:0)
我所做的是从我的CountDownTimer类的Activity调用一个方法,如下所示:
//Timer Class inside my Activity
public class Splash extends CountDownTimer{
public Splash(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
}
@Override
public void onFinish() {
nextActivity(Login.class, true);
}
@Override
public void onTick(long millisUntilFinished) {}
}
//Method on my Activity Class
protected void nextActivity(Class<?> myClass, boolean finish) {
Intent myIntent = new Intent(this, myClass);
myIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(myIntent);
if(finish)
finish();
}