我正在制作简单的 Android 应用程序,它应该有一个从 60 秒计数到 0 秒的计数器。我有一个想法如何做到这一点,但我不确定这是否是最明智的方法。而且我不确定如何让它在代码中工作。
想法: 在 .xml 文件中,我添加了 textView。我将创建扩展 Service 的 MyService 类,该类将由 OnCreate 函数内的 .java 文件调用(因为我希望立即开始计数)。 MyService 每秒都会更改 textView 的内容(我将有 int 计数器,该计数器每秒都会减少,然后 textView 的文本将会更改)。
有没有更好的方法?
这是 MyService 类:
public class MyService extends Service {
//for timer:
int counter = 0;
static final int UPDATE_INTERVAL = 1000;
private Timer timer = new Timer();
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
doSomethingRepeatedly();
return START_STICKY;
}
private void doSomethingRepeatedly() {
timer.scheduleAtFixedRate( new TimerTask() {
public void run() {
//code for changing the content
}
}, 0, UPDATE_INTERVAL);
}
@Override
public void onDestroy() {
super.onDestroy();
//za timer
if (timer != null){
timer.cancel();
}
}
}
我必须将此代码放在单独的 .java 文件中吗?
我不确定如何编写代码来更改textView的内容,因为我不确定是否可以调用textView的id,因为它位于单独的文件中?
这些将是启动服务的函数:
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
我必须把它们放在哪里?
最佳答案
使用 CountDownTimer .
Schedule a countdown until a time in the future, with regular notifications on intervals along the way. Example of showing a 30 second countdown in a text field:
new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
The calls to onTick(long) are synchronized to this object so that one call to onTick(long) won't ever occur before the previous callback is complete. This is only relevant when the implementation of onTick(long) takes an amount of time to execute that is significant compared to the countdown interval.
关于java - 在 android eclipse 中创建第二个计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28394262/