'Unable to run timer in Background using foreground service, making a count up timer to keep running in background even if user kills the app

This is the code for timer in mainactivity:

I am trying to run this in background with foreground service but if i put the whole code in the onCreate, the app gets crashed. I want the timer to be running even if user kills the app.

public class MainActivity2 extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

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

        Intent intent = new Intent(this,MyService.class);

        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(timerStarted == false)
                {
                    timerStarted = true;
                    start.setText("Pause");
                    startTimer();
                    startForegroundService(intent);
                }
                else
                {
                    timerStarted = false;
                    start.setText("Start");

                    timerTask.cancel();
                }

                }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                timerTask.cancel();
                time = 0.0;
                timerText.setText(formatTime(0,0,0));
                start.setText("Start");
            }
        });

        timer = new Timer();
        TimerTask timerTask;
        Double time = 0.0;



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source