0

I am trying to create a countdowntimer which will run even though the app is sent to the background? I am not sure how to implement this using services, so would it be possible to run it in the doBackground method of a asyncTask, and will the timer continue to run even when the app is "minimized"?

thanx

Bohrend
  • 1,467
  • 3
  • 17
  • 26
  • 1
    No. AsyncTask is still bound to the context so if your context gets killed, it will cancel. You need to use a service. – CodingIntrigue Nov 08 '13 at 09:25
  • No u have to make service – SweetWisher ツ Nov 08 '13 at 09:25
  • thax for reply, how can I create a service with a countdown timer? I simply want the service to run the entire time, and countdown, however how do I notify the service once the countdown has expired and the call the onDestroy() method? – Bohrend Nov 08 '13 at 09:28
  • 1
    @user2042227 I believe the question is correctly answered and you shouldn't use comments to ask a second question. To be honest that 2nd question is not even valid for StackOverflow criteria. I suggest you first have a good read and a good try to implement the Service yourself. – Budius Nov 08 '13 at 09:31
  • Please check [this](http://stackoverflow.com/a/8123675/2591002) – SweetWisher ツ Nov 08 '13 at 09:45

2 Answers2

5

doInBackgroud() runs on a different thread. But it does not means it isnt bound with the app. If the app stops, AsyncTask stop with it. So your timer would be of no help here.

What you can do is, use AlarmManager to call a BroadcastReceiver denoting that the timer's up. This BroadcastReceiver can in turn call up a Service or Activity in which you can do whatever you like.

d3m0li5h3r
  • 1,957
  • 17
  • 33
0

If you want to using asynctask to run countdown timer and if you want to show on UI, you can not use doInBackground, because it can not meddle to UI.

I think you should use thread for this issue. if you want/dont want timer continue to run when the app is minimize, you can use a boolean variable to control (must use runOnUiThread to meddle to UI)

How to use:

    boolean stop=false;
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            // TODO Auto-generated method stub
            if (!stop) {
                //YOUR CODE HERE
            }
        }
    });

If you want to stop timer when app minimize, use can set stop=true in onPause() of activity

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    stop=true;
}

and if you want timer re-play when activity resume, you can set stop=false in onResume()

@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    stop=false;
}
Quoc Truong
  • 545
  • 4
  • 9