【发布时间】:2015-02-08 13:09:02
【问题描述】:
我正在制作简单的 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));
}
我必须把它们放在哪里?
【问题讨论】:
-
如果有帮助,请检查此stackoverflow.com/questions/17620641/…