-1

How to make my stopwatch app running even after app has been closed completely ?

MainActivity.java

package com.study.meter;

import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Button;
import android.os.Handler;

import java.util.Locale;


public class MainActivity extends AppCompatActivity {

    public TextView StopWatch;
    public boolean isStopWatchRunning = false;
    public int stopWatchSecs = 0;

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

        // hide actionbar
        this.getSupportActionBar().hide();

        // set the value of StopWatch
        StopWatch = findViewById(R.id.StopWatch);
    }
    
    public void StartorStop(View v)
    {
        Button sv = (Button)v;
        if(isStopWatchRunning)
        {
            isStopWatchRunning=false;
            sv.setText("Start");
        }else
        {
            isStopWatchRunning=true;
            sv.setText("Stop");
        }
        // Creates a new Handler
        final Handler handler
            = new Handler();
  
        // Call the post() method,
        // passing in a new Runnable.
        // The post() method processes
        // code without a delay,
        // so the code in the Runnable
        // will run almost immediately.
        handler.post(new Runnable() {
            @Override
  
            public void run()
            {
                int hours = stopWatchSecs / 3600;
                int minutes = (stopWatchSecs % 3600) / 60;
                int secs = stopWatchSecs % 60;
  
                // Format the stopWatchSecs into hours, minutes,
                // and stopWatchSecs.
                String time
                    = String
                          .format(Locale.getDefault(),
                                  "%d:%02d:%02d", hours,
                                  minutes, secs);
  
                // Set the text view text.
  
                // If running is true, increment the
                // stopWatchSecs variable.
                if (isStopWatchRunning) {
                    StopWatch.setText(time);
                    stopWatchSecs++;
                    handler.postDelayed(this, 1000);
                }
  
                // Post the code again
                // with a delay of 1 second.
            }
        });
    }
}

This however restarts the stopWatch when app has been closed, How to make this stopwatch not to stop after app has been closed or destroyed or device has been restarted or switched off?

I meant to say I want it to keep running in background

Edit

maybe like this mathematical equation

Time when app closed = 14:20:-00 StopWatch's reading when app closed = 23 secs (save this data into storage)

Time when app reopend = 14:25:00 Last reading of stopwatch = 23 secs

so, value of stopwatch will be = (14:25:00 - 14:20:00)+23 secs = 5mins + 23 secs = 323secs

leftclick
  • 126
  • 10
  • you want your app to keep running after it's closed completely? How would that work? – Stultuske Sep 09 '21 at 08:29
  • I want to keep running it in background – leftclick Sep 09 '21 at 08:33
  • Does this answer your question? [Creating Background Service in Android](https://stackoverflow.com/questions/9177212/creating-background-service-in-android) – Khaby Lame Sep 09 '21 at 08:48
  • see the mathematical equation in what i edited. – leftclick Sep 09 '21 at 08:53
  • Maybe like this because this will not eat memory in backround – leftclick Sep 09 '21 at 08:53
  • @leftclick yeah, I had seen your mathematical equation. But you have mentioned *I want to keep running it in background*, then follow El primo suggestion. Your mathematical equation is dangerous what if the user changed time locally after closing your app? Just run a service to track seconds until the stopwatch is stopped. – Udhaya Sep 09 '21 at 10:05
  • @leftclick there is no large memory usage in a stopwatch app, until and unless you start using high quality images in your app. There are many stopwatch apps in the market, they dont consume too much memory – Khaby Lame Sep 10 '21 at 05:50
  • Even your alarm app should consume only 20-30MB ram – Khaby Lame Sep 10 '21 at 05:50
  • Plus there are lot new cheaper phones with high memory in the market. Who uses 2GB ram mobile? – Khaby Lame Sep 10 '21 at 05:50
  • Yeah @Udhaya I agree with you. User can change time for any purpose. What if a user has their clock 15-20min ahead? – Khaby Lame Sep 10 '21 at 05:53

3 Answers3

0

In theory, you could store the start time of the timer in a local storage and resume when the app starts again based on that value.

karsep5
  • 72
  • 8
  • No I want to continue it in backround. – leftclick Sep 09 '21 at 08:35
  • if i save it as you said, for-example 3mins then this will resume at 3mins. – leftclick Sep 09 '21 at 08:36
  • 1
    No @leftclick - this **is** the correct solution / answer. The user does not care about the stopwatch running in the background and neither should you. If I start the watch at t=2, terminate the app at t=5 where the current displayed time is 5-2=3 and reopen at t=17 you can simply and safely display 17-2=15 as the current stopped time value. – luk2302 Sep 09 '21 at 08:39
  • so it means I will use time to display the stopwatch – leftclick Sep 09 '21 at 08:42
  • you want to say the solution will be if i click on start on 14:13:45 then close the app on 14:14:00 then my app will store the stopwatch value and time of closing – leftclick Sep 09 '21 at 08:45
  • And what do you mean by local storage? – Khaby Lame Sep 09 '21 at 08:46
  • The OP wants to run the timer in background regardless if the app is closed or not – Khaby Lame Sep 09 '21 at 08:47
  • @ElPrimo we know that OP wants that but we are saying there is no point in doing it. – luk2302 Sep 09 '21 at 13:44
  • It's the OP's choice. He/She can do anything. – Khaby Lame Sep 09 '21 at 14:11
  • Plus I am asking the answeer that what does it mean by local storage. – Khaby Lame Sep 09 '21 at 14:12
  • @luk2302 I have also suggested an question in the comment section. This question may be a duplicate. – Khaby Lame Sep 10 '21 at 05:46
  • There are many videos on youtube trying to do the same as the OP is saying – Khaby Lame Sep 10 '21 at 05:48
  • Whatsapp has a service, Chrome has a service every app has a foreground service. – Khaby Lame Sep 10 '21 at 05:53
  • You can see ongoing services in your phone and then you will realise how apps use services. – Khaby Lame Sep 10 '21 at 05:54
  • To do this, you have to turn on developer options on your mobile. Then enable it. Scroll down a little bit and you will find a option named "running". Click on running and you will see all the ongoing services and cached services. – Khaby Lame Sep 10 '21 at 05:56
  • @leftclick If you are looking for an option to keep the app running in the background, then you would have to make use of background services in android. What I assumed was you wanted the timer to continue and resume even if the app is not running. To do it, you store the start time of when the timer was started in a local storage(could be a file or sqlite table entry). When the app starts, look for the presence of that entry and resume based on the start time. So, even if the app was not running in between, you still know what the current value of the timer has to be. Refer luk2303's example – karsep5 Sep 10 '21 at 06:08
  • what do you mean by local storage. You can use SharedPreferences – Khaby Lame Sep 10 '21 at 11:42
0

Try using JobScheduler to achieve this.

Udhaya
  • 335
  • 3
  • 12
0

You have to make a Service that will run in the background. Whatsapp has a service in the background, so whenever a new notification comes and it is closed completely, then also notification appears.

See these links for reference:

Creating Background Service in Android

Android Developer Doc

Edit: Put your timer code inside a class that extends a Service

Khaby Lame
  • 228
  • 2
  • 16