1

我做了一个显示当前时间的 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;
}


}
4

1 回答 1

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);
于 2012-08-01T10:29:31.033 回答