服务在 onCreate() 方法中一遍又一遍地运行 AsyncTask
我有一个在发送警报时运行的服务。
问题是该服务每隔几个小时就会自动运行一次。
我只希望它在执行警报时运行一次。
这是我正在使用的代码:
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
loadList service_release = new loadList();
service_release.execute();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return startId;
}
@Override
public void onCreate(){
super.onCreate();
loadList service_release = new loadList();
service_release.execute();
}
有人告诉我应该将 AsyncTask 移动到 onStartCommand() 中执行。但我在文档中没有看到任何可以通过这样做解决我的问题的内容。
我需要做什么才能让它运行一次并且在警报触发后的一段时间内不不断运行?
编辑:
我的闹钟是这样设置的..
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager)getSystemService(alarm);
Intent Aintent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.FRIDAY, );
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 4 * AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pi);
I have a Service that i run when a alarm is sent.
The problem is the service runs ever couple of hours automatically.
I only want it to run once when the alarm is executed.
Here is the code i am using:
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onStart(Intent intent, int startId) {
loadList service_release = new loadList();
service_release.execute();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return startId;
}
@Override
public void onCreate(){
super.onCreate();
loadList service_release = new loadList();
service_release.execute();
}
Someone told me i should move the AsyncTask to execute in onStartCommand(). But i didnt see anything in the docs that will fix my problem by doing this.
What do i need to do for it to run once and dont kepp running over and over throughout a time period after the alarm is set off?
EDIT:
My Alarm is being set up like this..
String alarm = Context.ALARM_SERVICE;
AlarmManager am = (AlarmManager)getSystemService(alarm);
Intent Aintent = new Intent("REFRESH_THIS");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, Aintent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.FRIDAY, );
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 4 * AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pi);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您有一个重复警报,这意味着它将被重复触发,并且每次都会启动该服务。如果您不需要重复,请使用
AlarmManager.set()
设置不重复警报。You have a repeating alarm, that means it will be triggered repeatedly, and launch the service each time it is. If you don't need it to repeat, set a non-repeating alarm, using
AlarmManager.set()
.