每分钟运行一次的服务

编程入门 行业动态 更新时间:2024-10-26 14:36:36
本文介绍了每分钟运行一次的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一项服务,我想在后台每分钟执行一次任务.它不需要在手机休眠时执行任务,只有在用户积极使用它时才需要执行任务.我正在尝试使用如下设置的 IntentService 来执行此操作:

I have a service that I am wanting to execute a task every minute in the background. It does not need to execute the task whenever the phone is asleep, only when the user is actively using it. I am trying to do this with an IntentService which is set up as follows:

public class CounterService extends IntentService{ public CounterService() { super("CounterService"); } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent,flags,startId); } @Override protected void onHandleIntent(Intent intent) { Toast.makeText(this, "onhandleintent", Toast.LENGTH_SHORT).show(); while(true) { //one minute is 60*1000 try { Thread.sleep(5 * 1000); Toast.makeText(getApplicationContext(), "getting app count", Toast.LENGTH_LONG).show(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }

现在为了使功能正常工作,我只是希望它每 5 秒显示一次祝酒词,我会将其更改为一分钟后.如果我将 while(true) 注释掉,则会显示onhandleintent"消息.但是,如果我运行以下代码,则 Toasts 都不会显示.我该如何解决这个问题?

Right now to get the functionality working I simply want it to display a toast every 5 seconds, I will change it to one minute later. If I have the while(true) commented out, then the "onhandleintent" message is displayed. However if I have the following code run, neither of the Toasts display. How can I fix this?

推荐答案

这将每分钟向您的服务发送一个意图,而不会在您的活动中使用任何处理器时间

This will send an intent to your service every minute without using any processor time in your activity in between

Intent myIntent = new Intent(context, MyServiceReceiver.class); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0); AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.add(Calendar.SECOND, 60); // first time long frequency= 60 * 1000; // in ms alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, pendingIntent);

调整 MyServiceReceiver.class 以匹配您的目标服务或活动.文档 提供了更多详细信息来微调您的调用,例如您是否需要准确的时间,在一天中的特定时间执行...

Adjust MyServiceReceiver.class to match your target service or activity. The documentation provides more details to fine-tune your calls like whether you want exact timing, execution at a specific time of the day ...

更多推荐

每分钟运行一次的服务

本文发布于:2023-06-07 15:29:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/568628.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:每分钟

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!