首页 > 解决方案 > 即使应用程序关闭,倒数计时器如何继续运行?

问题描述

我想用倒数计时器禁用任务 1 小时。但是当应用程序关闭时,倒数计时器停止工作

我已经尝试过 Intent 服务,但似乎它不起作用

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
    }
};

标签: androidcountdowntimer

解决方案


您可以AlarmManager用于执行应用程序生命周期之外的任务。设置闹铃时间时,只需计算 1 小时后的时间,然后为该时间设置闹铃。您可以在此处查看文档:https ://developer.android.com/training/scheduling/alarms


推荐阅读