在这个 android 服务中,我想在当前时间显示第二个值的祝酒词。但这一次又一次地显示相同的值。计时器计划以 1 秒的间隔更新,但值不会刷新,并且 toast 会再次显示先前的值。我不知道是什么问题。
package net.learn2develop.Services;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.widget.Toast;
public class MyService extends Service{
Handler handler = new Handler();
Calendar c = Calendar.getInstance();
Timer t = new Timer();
int second = c.get(Calendar.SECOND);
int temp = 6;
@Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
public int onStartCommand(Intent intent, int flags, int startId){
Toast.makeText(this,"service started",Toast.LENGTH_SHORT).show();
TimerTask task = new TimerTask() {
@Override
public void run() {
second = timeSecond();
handler.post(new Runnable() {
@Override
public void run() {
// Toast.makeText(getBaseContext(),String.valueOf(second), Toast.LENGTH_SHORT).show();
}
});
}
};
t.scheduleAtFixedRate(task, 0, 4* 1000);
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
t.cancel();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
}
public int timeSecond() {
handler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(getBaseContext(),String.valueOf(c.get(Calendar.SECOND)), Toast.LENGTH_SHORT).show();
}
});
return c.get(Calendar.SECOND);
}
}