Manish Stark
Manish Stark

Reputation: 161

How can countdown timer continue running even if app if close?

I want to disable tasks for 1 hour with countdowntimer. but when app is close, countdowntimer is stop working

I have tried Intent service but seems like its not working

final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
Context mContext;

public IBinder onBind(Intent intent) {
    return null;
}

public void onCreate() {
    super.onCreate();
    mContext = this;
    startService();
}

private void startService() {
    scheduler.scheduleAtFixedRate(runner, 0, 30, TimeUnit.SECONDS);
}

final Runnable runner = new Runnable() {
    public void run() {
        mHandler.sendEmptyMessage(1212);
        Toast.makeText(mContext, "TImer is out", Toast.LENGTH_SHORT).show();
    }
};

public void onDestroy() {
    super.onDestroy();
    Toast.makeText(this, "Service Stopped ...", Toast.LENGTH_SHORT).show();
}

private final Handler mHandler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        //do what ever you want as 3hrs is completed
    }
};

Upvotes: 0

Views: 456

Answers (2)

Ankit
Ankit

Reputation: 1068

You can use JobScheduler like this:

private static final int JOB_ID=1;

JobScheduler mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID, new ComponentName(getPackageName(),SchedulerService.class.getName()));
builder.setMinimumLatency(60 * 60 * 1000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
mJobScheduler.schedule(builder.build());

SchedulerService is your scheduling service

public class SchedulerService extends JobService {
private static final String TAG = "SchedulerService";
@Override
public boolean onStartJob(JobParameters params) {
    // resume your work
    return false;
}

@Override
public boolean onStopJob(JobParameters params) {
    return false;
}}

Upvotes: 0

Aram Sheroyan
Aram Sheroyan

Reputation: 588

You can use AlarmManager for performing tasks outside of your app's lifetime. When setting the time for the alarm, simply calculate the time after 1 hour and set alarm for that time. You can check the docs in here: https://developer.android.com/training/scheduling/alarms

Upvotes: 1

Related Questions