How to run a timer in the background ?

Evan Laksana

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);
        }

    };

thank you anyway

Hitesh Sahu

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);

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();
        }
    };

}

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();

        }
    });

Adding AppController

enter image description here

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to run a background timer in Python

From Dev

Android run a timer in the background

From Dev

iOS Timer run in background

From Dev

iOS Timer run in background

From Dev

Run timer in background

From Dev

How to run a background service on demand - not on application startup or on a timer

From Dev

How to run timer though the app entered background or is terminated

From Dev

Can counter/timer run in background?

From Dev

Run timer in 'background' when app is closed

From Dev

Run timer in 'background' when app is closed

From Dev

UWP timer background task doesn't run

From Dev

How to make a timer app that could run even when the app is in the background mode

From Dev

Is it possible to run the countup timer app to run in background on Windows Phone 7?

From Dev

How to run a timer inside a QThread?

From Dev

how to countdown timer run in reactnative

From Dev

Swift - Best way to run timer in background for iphone apps

From Dev

Timer in Background

From Dev

Timer in Background

From Dev

How to prevent drift on short background timer?

From Dev

How to prevent drift on short background timer?

From Dev

Timer and TimerTask - how to reschedule Timer from within TimerTask run

From Dev

How to run timer and AI logic in Swift simultaneously

From Dev

How to run Timer Task with dynamic changeable time?

From Dev

How to run php code in javascript timer/loop

From Dev

How to run Timer Task with dynamic changeable time?

From Dev

How to run command then timer is ended ? C#

From Dev

I want my timer to run in background but it stops as soon it goes in background android

From Dev

How to run a command in the background on Windows?

From Dev

How to run a subprocess in the background python

Related Related

  1. 1

    How to run a background timer in Python

  2. 2

    Android run a timer in the background

  3. 3

    iOS Timer run in background

  4. 4

    iOS Timer run in background

  5. 5

    Run timer in background

  6. 6

    How to run a background service on demand - not on application startup or on a timer

  7. 7

    How to run timer though the app entered background or is terminated

  8. 8

    Can counter/timer run in background?

  9. 9

    Run timer in 'background' when app is closed

  10. 10

    Run timer in 'background' when app is closed

  11. 11

    UWP timer background task doesn't run

  12. 12

    How to make a timer app that could run even when the app is in the background mode

  13. 13

    Is it possible to run the countup timer app to run in background on Windows Phone 7?

  14. 14

    How to run a timer inside a QThread?

  15. 15

    how to countdown timer run in reactnative

  16. 16

    Swift - Best way to run timer in background for iphone apps

  17. 17

    Timer in Background

  18. 18

    Timer in Background

  19. 19

    How to prevent drift on short background timer?

  20. 20

    How to prevent drift on short background timer?

  21. 21

    Timer and TimerTask - how to reschedule Timer from within TimerTask run

  22. 22

    How to run timer and AI logic in Swift simultaneously

  23. 23

    How to run Timer Task with dynamic changeable time?

  24. 24

    How to run php code in javascript timer/loop

  25. 25

    How to run Timer Task with dynamic changeable time?

  26. 26

    How to run command then timer is ended ? C#

  27. 27

    I want my timer to run in background but it stops as soon it goes in background android

  28. 28

    How to run a command in the background on Windows?

  29. 29

    How to run a subprocess in the background python

HotTag

Archive