我正在设计一个倒计时计时器,它工作得很好,但前提是我要留在这个Activity。因为,如果倒计时开始,然后我返回,例如启动otherActivity,则倒计时将跟随倒计时。从逻辑上讲,如果我再次启动倒计时计时器所在的活动,它看起来好像什么都没有倒计时,但是在bacground中倒计时,我知道,因为在计时器的ontick上,我抛出一个continue通知,在notification选项卡上显示它。
代码如下所示,sendNotification方法是一种在时间结束时抛出警报的方法,而sendnotificationTiempo则是每秒向选项卡发送一个通知,并显示在顶部。

public static final int NOTIFICATION_ID = 33;
public static final int NOTIFICATION_ID_Tiempo = 34;
private int minCrono;
TextView text;
MyCounter timer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    StartCrono = (Button) findViewById(R.id.butt_start);
    CancelCrono = (Button) findViewById(R.id.butt_cancel);
    text=(TextView)findViewById(R.id.text_countTime1);

    CancelCrono.setEnabled(false);


    minCrono = mins.getCurrentItem();

    StartCrono.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            minCrono=(60000*minCrono);
            timer = new MyCounter(minCrono,1000);
            timer.start();
        }
    });

    CancelCrono.setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            timer.cancel();
            text.setText("El tiempo se ha cancelado");
            minutosCrono =  mins.getCurrentItem();

            if (mNotificationManager != null)
                mNotificationManager.cancel(NOTIFICATION_ID_Tiempo);

        }
    });
}

倒计时类:
public class MyCounter extends CountDownTimer{
    public MyCounter(long millisInFuture, long countDownInterval) {
        super(millisInFuture, countDownInterval);
    }
     @Override
    public void onFinish() {

        StartCrono.setEnabled(true);
        CancelCrono.setEnabled(false);
        mins.setEnabled(true);
        minCrono = mins.getCurrentItem();
        //

        text.setText("Time Complete!");

        sendnotification("Guau", "Time finished.");

    }
    @Override
     public void onTick(long millisUntilFinished) {
        long segRestantesTotal=(millisUntilFinished/1000);
        long minRestantes= (segRestantesTotal/60);
        long segRestantes= (segRestantesTotal%60);


        if(segRestantes>=10){
            text.setText(minRestantes+":"+segRestantes);
            sendnotificationTiempo("Guau", minRestantes+":"+segRestantes);
        }
        else{
            text.setText(minRestantes+":0"+segRestantes);
            sendnotificationTiempo("Guau", minRestantes+":0"+segRestantes);
        }
    }
}

}
所以我要做的是,知道什么时候返回Activity并启动另一个,显示在后台倒数的时间,例如在textview中显示它。
或者如果我能从通知标签中得到倒计时的时间,那就太好了。
谢谢!

最佳答案

将myCounter实例移出活动。当活动重新启动时,将重新创建实例,以便旧实例消失。有几种方法可以做到这一点,但您需要让myCounter实例位于活动可以访问它但不负责其生命周期的地方。我使用我编写的一个基本的servicelocator实现,但是您可以很容易地创建一个自定义应用程序类,并将计时器(或创建和控制计时器的控制器类)保存在那里。

关于android - 捕获不同 Activity 中的倒数计时器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9485818/

10-12 00:10
查看更多