将倒计时器与异步任务一起使用

时间:2015-07-20 00:35:03

标签: android android-asynctask countdowntimer

我在使用倒计时器类实现异步任务时遇到问题。我有一个倒计时器来更新ui;但是,如果我去其他应用程序的时间从头开始,所以我需要使用异步任务。唯一的问题是我不知道如何将异步任务与我的倒计时器类合并,有人知道如何解决这个问题吗?

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_count_down);


        countDown = new CountDownTime(actualTimeFiniliazedInMilliSeconds, timeInterval);
       countDown.start();

        new UpdateCountDownTime().execute();



    }

    public class CountDownTime extends CountDownTimer {
        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountDownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onTick(long millisUntilFinished) {

            long millis = millisUntilFinished;
           hms = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));

            // currentCountDownTime.setText(currentCountDownTime.getText() + String.valueOf(millisUntilFinished));
            timeTextView.setText(hms);
        }

        @Override
        public void onFinish() {
           Intent goBack = new Intent(CountDownAct.this, ListOfAlarms.class);
            startActivity(goBack);
            finish();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        timeTextView.setText(hms);
    }

        private class UpdateCountDownTime extends AsyncTask<Void, Void, Void> {
            @Override
            protected Void doInBackground(Void... params) {
                countDown = new CountDownTime(actualTimeFiniliazedInMilliSeconds, timeInterval);
                countDown.start();
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                ((TextView) findViewById(R.id.timeTextView)).setText(hms);
            }

     }

2 个答案:

答案 0 :(得分:0)

在活动中创建一个CountDownTime实例作为静态字段变量:

    private static CountDownTime sCountDownTime = new CountDownTime(20000, 1000);

然后在您需要的任何地方开始活动:

    sCountDownTime.start(this);

这是修改后的CountDownTime类,使其静态,因此它不会保留对outter活动的强引用。如果要执行代码,即使启动此计数器的活动已完成\销毁(等用户按下后退键),也可能需要删除activity.isFinishing \ isDestroyed。

    public static class CountDownTime extends CountDownTimer {

        private WeakReference<Activity> mActivityRef;
        private String mCurrentTime;
        private boolean mStarted;

        public CountDownTime(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        public void start(Activity activity) {
            mActivityRef = new WeakReference<Activity>(activity);
            if (!mStarted) {
                mStarted = true;
                start();
            } else {
                updateTextView();
            }
        }

        @Override
        public void onTick(long millisUntilFinished) {
            long millis = millisUntilFinished;
            mCurrentTime = String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
                    TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
                    TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
            updateTextView();
        }

        @Override
        public void onFinish() {
            Activity activity = mActivityRef.get();
            if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
                activity.startActivity(new Intent(activity, SettingsActivity.class));
                activity.finish();
            }
            mStarted = false;
        }

        private void updateTextView() {
            Activity activity = mActivityRef.get();
            if (activity != null && !activity.isFinishing() && !activity.isDestroyed()) {
                TextView textView = (TextView) activity.findViewById(R.id.text_view);
                textView.setText(mCurrentTime);
            }
        }
    }

答案 1 :(得分:0)

尝试以下代码。我把倒数减少了3分钟。我在首选项中保存onStop()中的当前时间戳,而在onResume()中,我正在进行一个小计算,以确定从倒计时开始的时间。

 public class MainActivity extends Activity {
TextView textView;
private CountDownTime countDownTimer;
private PreferenceManager manager;
private String EXIT="exit",TIME_LAPSED="timeLapsed";
private long millisInFuture=3*60*1000;
private long countDownInterval=1000;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    textView=(TextView)findViewById(R.id.textView1);
    manager=new PreferenceManager();


}
    @Override
      protected void onResume() {
super.onResume();
    if(manager.getLong(this, EXIT)<0){
countDownTimer=new CountDownTime(millisInFuture, 1000);
    }else{
         long time = manager.getLong(this,TIME_LAPSED)- (System.currentTimeMillis() -                               manager.getLong(this, EXIT)); 
    countDownTimer=new CountDownTime(time, countDownInterval);
            }
            Log.e("ONRESUME ", "CALLED");
             countDownTimer.start();
           }
 @Override
        protected void onStop() {
manager.put(this, EXIT, System.currentTimeMillis());
manager.put(this, TIME_LAPSED, millisInFuture);
countDownTimer.cancel();
super.onStop();
Log.e("ONSTOP ", "CALLED");
}
        public class PreferenceManager {
       private static final String PREF_NAME = "app_pref";
         public PreferenceManager() {};
           private  SharedPreferences getSharedPreferences(Context context) {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
            }
         private  Editor getPreferenceEditor(Context context) {
        return getSharedPreferences(context).edit();
        }
    public  long getLong(Context context, String key) {
        return getSharedPreferences(context).getLong(key, -1);
        }
        public  void put(Context context, String key, long value) {
    Editor editor = getPreferenceEditor(context);
    editor.putLong(key, value);
    editor.commit();
}
 }
public class CountDownTime extends CountDownTimer {
   public CountDownTime(long millisInFuture, long countDownInterval) {
    super(millisInFuture, countDownInterval);
    }
   @Override
public void onTick(long millisUntilFinished) {
    millisInFuture = millisInFuture - 1000;
    long millis = millisUntilFinished;
    textView.setText(String.format("%02d:%02d:%02d", TimeUnit.MILLISECONDS.toHours(millis),
            TimeUnit.MILLISECONDS.toMinutes(millis) - TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
            TimeUnit.MILLISECONDS.toSeconds(millis) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis))));
}
    @Override
    public void onFinish() {
   /*Intent goBack = new Intent(CountDownAct.this, ListOfAlarms.class);
    startActivity(goBack);
    finish();*/
}
 } }