- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
我创建了一个每 5 秒启动一次服务的警报管理器,该应用程序运行良好但几个小时后警报管理器停止运行。请注意,该应用程序未被用户使用,这意味着它在没有用户交互的情况下在后台运行。有谁知道如何每隔几秒启动一次服务而不停止?
AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + (1000 * 60 * 5), pi);
最佳答案
不要对警报管理器做这样的事情。报警管理器更多应该在几个小时内完成的任务的概念(在最佳情况下)。
如果您需要精确处理您的任务,请在内部使用处理程序服务,该帖子执行您的可运行。在您的 runnable 中,调用该方法以再次执行 runnable。
将runnable和handler保存为服务的成员变量并make过程很粘。如果你想停止服务和处理程序(处理程序不会如果你只是调用 stopService(Context) 或 Service.stopSelf(),你需要停止在处理程序上使用您的可运行对象调用 removeCallbacks(runnable)。
干杯。
顺便说一句:考虑一下您是否真的想要每 5 秒启动一次服务。也许只是在服务的可运行内部做服务工作我刚刚描述了。
Edit2:如果您需要服务可靠,请为启动操作添加一个 BroadcastReceiver,它将在启动时接收广播并重新启动您的服务。
Edit3:在不启动服务的情况下检查您的服务是否正在运行的代码:
public static boolean isRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (YourService.class.getName().equals(service.service.getClassName())){
return true;
}
}
return false;
}
但是,尽管如此,请在 onStartCommand 中检查您的成员“处理程序”是否为空如果是这样,请忽略启动请求,因为这可能会导致您遇到多个可运行处理的情况。
编辑4:
服务代码 fragment :
public class LoopingServiceSnipped extends Service{
public static final long STANDARD_FREQUENCY = 1000;
private static long loopingFrequency = STANDARD_FREQUENCY;
private Handler serviceHandler;
private Runnable loop;
//EXTRAS
private static final String INTENT_EXTRA_STOP_SERVICE = LoopingServiceSnipped.class.getSimpleName() + "_INTENT_EXTRA_STOP_SERVICE";
private static final String INTENT_EXTRA_FREQUENCY = LoopingServiceSnipped.class.getSimpleName() + "_INTENT_EXTRA_FREQUENCY";
/**
* Determines if the service is running (reliably) without starting it.
*
* @param context
* needed for SystemServices
*
* @return true if the service is running
*/
public static boolean isRunning(Context context) {
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (LoadingScreenAppDetectionService.class.getName().equals(service.service.getClassName())){
return true;
}
}
return false;
}
public static void stopService(Context c) {
Intent i = new Intent(c, LoopingServiceSnipped
i.putExtra(INTENT_EXTRA_STOP_SERVICE, true);
c.startService(i);
}
public static synchronized void setFrequency(Context c, long frequency) {
Intent i = new Intent(c, LoadingScreenAppDetectionService.class);
i.putExtra(INTENT_EXTRA_FREQUENCY, frequency);
c.startService(i);
}
@Override
public void onCreate() {
super.onCreate();
init();
}
private void init() {
//do your initialization here
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (shouldStopService(intent)){
LOG.d("Going to stop service!");
tryStopService();
return Service.START_NOT_STICKY;
} else {
return startOrContinueService(intent);
}
}
private void tryStopService() {
stopLooping();
stopSelf();
}
private void stopLooping() {
if (serviceHandler != null){
serviceHandler.removeCallbacks(getLoop());
serviceHandler = null;
}
}
private int startOrContinueService(Intent intent) {
if (hasNewFrequency(intent)){
setFrequency(intent);
stopLooping();
}
if (!isServiceRunning()){
startLooping();
}
} else {
LOG.d("Going to continue with service!");
}
return Service.START_STICKY;
}
private boolean hasNewFrequency(Intent intent) {
return intent.hasExtra(INTENT_EXTRA_FREQUENCY);
}
private void setFrequency(Intent intent) {
if (intent.hasExtra(INTENT_EXTRA_FREQUENCY)){
loopingFrequency = intent.getLongExtra(INTENT_EXTRA_FREQUENCY, STANDARD_FREQUENCY);
}
}
private boolean isServiceRunning() {
return serviceHandler != null;
}
private boolean shouldStopService(Intent i) {
if (i.hasExtra(INTENT_EXTRA_STOP_SERVICE)){
return i.getBooleanExtra(INTENT_EXTRA_STOP_SERVICE, false);
} else {
return false;
}
}
private void startLooping() {
if (serviceHandler == null){
serviceHandler = new Handler();
}
serviceHandler.postDelayed(getAppDetectionLoop(), getFrequency());
}
private Runnable getLoop() {
if (loop == null){
loop = new Runnable() {
@Override
public void run() {
//do your looping work here
startLooping();
}
};
}
return loop;
}
另外添加Boot Receiver和Screen TurnOn Receiver。
关于android 闹钟管理器在几个小时后停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32146221/
我有 0 小时、3 小时、12 小时、24 小时、48 小时的数据组……我想绘制这些数据的图表,以便保留时间的比例。 runs <- c(1:25) hours <- as.factor(c(0, 3
例如,如果我选择了时间:下午 3 点和小时数:5 小时,则得到 (8pm) 作为答案“ 最佳答案 let calendar = Calendar.current let date = calendar
我有一个包含两个日期时间字段的表单。用户输入日期 (yyyy-mm-dd) 和时间(3 个框;小时、分钟、上午/下午)。 出于某种原因,第一个没有保存为 24 小时制。 以下数据为输入结果: 2011
我一直在尝试使用导出单位进行计算,但到目前为止我还没有取得任何成果。 我已经尝试过mathjs ,但如果我输入 1 小时 * 1 英里/小时,我会得到 UnsupportedTypeError: Fu
我有两组要运行的 cronjob。第一个应该每 3 小时运行一次,第二个也应该每 3 小时运行一次,但比第一组晚一个小时。什么是正确的语法? // every 3 hours 17 */3 * *
我知道 AWS 中的预留实例更多的是计费而不是实际实例——它们没有附加到实际实例——我想知道: 如果我在特定区域和可用区中购买特定时间的预留实例 - 如果我每天 24 小时使用单个实例与运行 24 个
我试过: seq( from=as.POSIXct("2012-1-1 0", tz="UTC"), to=as.POSIXct("2012-1-3 23", tz="UTC"),
我有一个带有“日期”列的表。我想按小时分组指定日期。 最佳答案 Select TO_CHAR(date,'HH24') from table where date = TO_DATE('2011022
我知道如何在 SQL (SQL Server) 中获取当前日期,但要获取当天的开始时间: select dateadd(DAY, datediff(day, 0, getdate()),0) (res
我正在尝试在游戏之间创建一个计时器,以便用户在失去生命后必须等待 5 分钟才能再次玩游戏。但是我不确定最好的方法是什么。 我还需要它来防止用户在“设置”中编辑他们的时间。 实现这一目标的最佳方法是什么
我的查询有误。该错误显示预期的已知函数,得到“HOUR”。如果我删除这部分,查询将正常工作 (AND HOUR({$nowDate}) = 11) SELECT c FROM ProConvocati
var d1 = new Date(); var d2 = new Date(); d2.setHours(d1.getHours() +01); alert(d2); 这部分没问题。现在我试图在 (
我正在构建一个用于练习的基本时钟应用程序,但出于某种原因,时间不会自动更改为最新的分钟或小时。例如,当前时间是 17:56,但它显示的是 17:54,这是我打开应用程序的最后时间。 NSDate *n
我创建了一张图片,我想将其用作页面的 hr。当它被上传时,它一直向左对齐。我希望它居中,在标题下。这是我的 CSS 代码: .section-underline { height: 35px
这个问题已经有答案了: Getting difference in seconds from two dates in JavaScript (2 个回答) 已关闭 4 年前。 我想计算两个具有不同格
我需要计算到某个日期/时间的剩余时间(天/小时)。 但是,我没有使用静态日期。 假设我在 每个星期日 的 17:00 有一个事件。我需要显示到下一个事件的剩余时间,即即将到来的星期日 17:00。 我
我正在执行这个脚本: SELECT EXTRACT(HOUR FROM TIMEDIFF('2009-12-12 13:13:13', NOW())); 我得到:-838。这是提取时 MySQL 可以
复制代码 代码如下: /** * 小时:分钟的正则表达式检查<br> * <br> * @param pInput 要检查的字符串 * @return boolean 返
连wifi5元/小时 独领风骚 朕好帅 今晚你是我的人 十里桃花 高端定制厕所VP专用 一只老母猪 在家好无聊 你爹的wifi 密码是叫爸爸全拼 关晓彤和鹿晗分手了吗 蹭了我的
我有以下数据框列: 我需要将 csv 列中的对象字符串数据转换为总秒数。 示例:10m -> 600s 我试过这段代码: df.duration = str(datetime.timedelta(df
我是一名优秀的程序员,十分优秀!