如何在后台运行计时器? [英] How to run a timer in the background ?

查看:38
本文介绍了如何在后台运行计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个计时器的代码,但是如果我更改片段,计时器将重置为 00:00 我希望该计时器在我单击停止或暂停后仍然计数,或者这意味着该计时器仍在后台计数怎么做 ?这是我的代码,

I have code for a timer , but if i change fragment the timer was reset to 00:00 i want that timer still count after i click stop or pause or that mean this timer still count in the background how to do it ? this is my code,

public class TimerFragment extends BaseFragment {
    private Button startButton;
    private Button pauseButton;
    private TextView timerValue;
    private long startTime = 0L;
    private Handler customHandler = new Handler();
    long timeInMilliseconds = 0L;
    long timeSwapBuff = 0L;
    long updatedTime = 0L;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_timer, container, false);

        initialize();
        //when start

        startTime = SystemClock.uptimeMillis();
        customHandler.postDelayed(updateTimerThread, 0);

        //pause
        pauseButton.setOnClickListener(new View.OnClickListener() {

            public void onClick(View view) {

                timeSwapBuff += timeInMilliseconds;
                customHandler.removeCallbacks(updateTimerThread);

            }
        });

        return rootView;
    }

    private Runnable updateTimerThread = new Runnable() {

        public void run() {

            timeInMilliseconds = SystemClock.uptimeMillis() - startTime;

            updatedTime = timeSwapBuff + timeInMilliseconds;

            int secs = (int) (updatedTime / 1000);
            int mins = secs / 60;
            secs = secs % 60;

            timerValue.setText("" + mins + ":"
                    + String.format("%02d", secs));
            customHandler.postDelayed(this, 0);
        }

    };

还是谢谢你

推荐答案

问题 :- 当你切换 Fragment 并回到 Timer Fragment 时,onCreate 生命周期回调将被调用,然后重置你的定时器在

Problem :- When you switch fragment and come back to Timer Fragment, the onCreate lifecycle callback will be called and that gone reset your timer in

customHandler.postDelayed(updateTimerThread, 0);

customHandler.postDelayed(updateTimerThread, 0);

解决方案:-将计时器逻辑移至活动类,但活动将在方向更改时重新创建,因此将计时器逻辑移至应用程序类:-

Solution :- Move timer logic to Activity class but activity will be recreate in orientation change so move timer logic into Application class :-

把这个类放到你的项目包中

Drop this class in you project package

import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Application;
import android.os.Handler;
import android.widget.Toast;

public class App extends Application {

    public static App appInstance;
    private SimpleDateFormat dateFormat;

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

        appInstance = this;

        dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
    }

    public void afficher() {
        Toast.makeText(getBaseContext(), dateFormat.format(new Date()), 300).show();
        handler.postDelayed(runnable,1000);
    }

    public void startTimer() {
        runnable.run();
    }

    public void stopTimer() {
        handler.removeCallbacks(runnable);
    }

    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        public void run() {
            afficher();
        }
    };

}

将您的应用程序名称设置为应用程序类,如下所示(应用程序的android名称属性):-

Set your Application name to App class like this below (android name property of application) :-

   <application
        android:name="com.masterdetail_webview.App"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.masterdetail_webview.TimertestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

现在您可以像这样从任何地方开始和停止计时器

Now you can start and stop timer simply like this from anywhere

findViewById(R.id.button1).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.startTimer();

        }
    });

    findViewById(R.id.button2).setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            App.appInstance.stopTimer();

        }
    });

添加应用控制器

这篇关于如何在后台运行计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆