Make a specific code run in background

android, background

Solution

Here is the code snippet for `AsyncTask`

private class AsyncTaskEx extends AsyncTask<Void, Void, Void> {

    /** The system calls this to perform work in a worker thread and
    * delivers it the parameters given to AsyncTask.execute() */
    @Override
    protected Void doInBackground(Void... arg0) {
        StartTimer();//call your method here it will run in background
        return null;
    }

    /** The system calls this to perform work in the UI thread and delivers
    * the result from doInBackground() */
    @Override
    protected void onPostExecute(Void result) {
        //Write some code you want to execute on UI after doInBackground() completes
        return ;
    }

    @Override
    protected void onPreExecute() {
        //Write some code you want to execute on UI before doInBackground() starts
        return ;
    }
}

Write this class inside your `Activity` and call where you want execute your method

new AsyncTaskEx().execute();

Problem

I would like to have this code run in the background. I can't figure out how to create a service or Asynstask, as most would point to, because it only needs to be this code, not everything else. ``` void StartTimer() { int minsTicks=CountM*60*1000; int hoursTicks=CountT*60*60*1000; int totalTicks=hoursTicks+minsTicks; mTextField = (TextView) findViewById(R.id.TimerTextView); CountDownTimer aCounter = new CountDownTimer(totalTicks, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText("seconds remaining: " + millisUntilFinished / 1000); } public void onFinish() { try { mTextField.setText("Kaffe Maskinen er igang"); mmOutputStream.write('2'); Thread.sleep(900000); mmOutputStream.write('0'); mTextField.setText("Kaffe Maskinen er slukket"); } catch (IOException e) {} catch (InterruptedException e) {} } }; aCounter.start(); } ```

Original source