我做了一项服务,显示一个显示当前时间的吐司。当“分钟”的值发生变化时,应显示Toast。我该怎么办 ? 这是代码。是否有必要创建一个监听器来监听分钟变量的变化? 请帮帮我。
public class Servicedemo extends Service{
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
String str;
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
str=String.valueOf(hour)+":"+String.valueOf(min);
Toast.makeText(this, str , Toast.LENGTH_SHORT).show();
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
答案 0 :(得分:2)
您需要创建一个timertask并覆盖run方法,例如:
public class yourAsyncTimerTask extends TimerTask{
@Override
public void run() {
Calendar c=Calendar.getInstance();
int hour=c.get(Calendar.HOUR);
int min=c.get(Calendar.MINUTE);
String str = String.valueOf(hour)+":"+String.valueOf(min);
Toast.makeText(this, str , Toast.LENGTH_SHORT).show();
}
}
并设置您的计时器
Timer timer = new Timer();
timer.schedule(new yourAsyncTimerTask(), 1 * 60 * 1000, 1 * 60 * 1000);