android - 即使应用程序关闭,倒数计时器如何继续运行?
问题描述
我想用倒数计时器禁用任务 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
}
};
解决方案
您可以AlarmManager
用于执行应用程序生命周期之外的任务。设置闹铃时间时,只需计算 1 小时后的时间,然后为该时间设置闹铃。您可以在此处查看文档:https ://developer.android.com/training/scheduling/alarms
推荐阅读
- node.js - 使用 xhr.open('post',url,true) 找不到文件 URL - 状态:404 node js
- azure - 使用 HTTP 请求将 Azure AD 组像普通 SharePoint 组一样添加到 SharePoint 站点/列表
- javascript - Framework7 中的自动完成和多个值
- c# - 在 C# 中使用 datatable 参数执行存储过程时出错
- dart - Flutter 中具有 Snap 效果的水平滚动卡片
- reactjs - 如何在反应js的导航中添加和删除活动类
- android - 我在导航抽屉内有一个微调器,当我选择一个微调器下拉项时,我正在打开一个活动,该活动有三个 TabLayout
- regex - 从 Oracle 消息错误中获取子字符串
- java - firebase 中的“equalTo”和“startAt & endAt”有什么不同,什么时候应该使用“equalTo”或“startAt 和 endAt”?
- javascript - 在 JavaScript 中访问 Office UI Fabric 主题颜色