0

我有一个显示倒计时的小部件。为此,我使用了 CountDownTimer 类,但问题是倒计时经常停止!我认为是因为 android 会在很多小时内自动停止线程,因为倒计时。如何解决这个问题?谢谢

public class TempoIndietro extends CountDownTimer{
     AppWidgetManager manager;
     ComponentName thisWidget;

    public TempoIndietro(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
        thisWidget = new ComponentName(context, widget.class); 
        manager = AppWidgetManager.getInstance(context);  
        remoteView = new RemoteViews(context.getPackageName(),R.layout.widgett);
    }

    @Override
    public void onFinish() {
    remoteView.setTextViewText(R.id.textView2, context.getResources().getString(R.string.onair_widget_countdown));
        manager.updateAppWidget(thisWidget, remoteView);
            }

            @Override
            public void onTick(long millisUntilFinished) {
                SimpleTimeFormat tf = new SimpleTimeFormat("$dd$ : $HH$: $mm$: $ss$");    
                String risultato = tf.format(millisUntilFinished); // arg0 tempo
                remoteView.setTextViewText(R.id.textView2, risultato);
                manager.updateAppWidget(thisWidget, remoteView);
            };
        }
4

1 回答 1

0

记住计时器的开始时间并计算与该时间的差。

您可以为此使用本地存储。

最好在 Activity 中的 onStop() 和 onResume() 中调用它。

节省:

SharedPreferences settings = getSharedPreferences("myappname", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putLong("varname", startDate.getTime());
editor.commit();

取回:

SharedPreferences settings = getSharedPreferences("myappname", 0);
Long millis = settings.getLong("varname", null);
Date startDate = new Date(millis);
于 2012-04-19T22:24:16.313 回答