0
votes

I'm working on foreground service and I want to stop foreground service at a specific amount of time but time can be changed through the user

let me show you the code

ForegroundServiceService.java

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

  // Some stuff Ex. Notification builder

            startTimer();
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    stopSelf();
                }
            }, periodValue);

    return START_STICKY;
}


private Timer timer;
private TimerTask timerTask;

 public void startTimer() {
        timer = new Timer();
        timerTask = new TimerTask() {
            public void run() {
                Log.i("Count", "=========  ");
            }
        };
        timer.schedule(timerTask, 1000, 1000); //
    }

here the period value for handler can be changed through user

MainActivity.java

public class DashboardActivity extends BaseActivity {


ActivityDashboardBinding activityDashboardBinding;
public static long periodValue = 30000L;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activityDashboardBinding = DataBindingUtil.setContentView(this, R.layout.activity_dashboard);

    activityDashboardBinding.btnAdd1Hour.setOnClickListener(view -> periodValue = periodValue + 15000);

}
}

the default value of periodValue is 30 second and when the service starts it automatically stop after 30 seconds but when the user adds more than 15 seconds still handler get only 30 seconds and automatically stop when 30 seconds is over.

My requirement is to stop service after 30 seconds but user can add more than 15 seconds to continue the service without restart service