运行每分钟服务 [英] Service that runs every minute
问题描述
我有,我想执行任务的背景下每分钟的服务。它并不需要执行任务时的电话是睡着了,只有当用户主动使用它。我试图用它建立了一个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秒钟,我会在以后更改为一分钟。如果我有,而(真)
注释掉,则显示onhandleintent的消息。但是,如果我有以下的code运行,无论是敬酒显示。我该如何解决这个问题?
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
这篇关于运行每分钟服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!