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