Android 在onCreate()方法中反复运行AsyncTask的服务
我有一个在发出警报时运行的服务 问题是这项服务会自动运行几小时 我只希望它在执行报警时运行一次 以下是我正在使用的代码:Android 在onCreate()方法中反复运行AsyncTask的服务,android,android-asynctask,android-service,Android,Android Asynctask,Android Service,我有一个在发出警报时运行的服务 问题是这项服务会自动运行几小时 我只希望它在执行报警时运行一次 以下是我正在使用的代码: @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onStart(Intent intent, int startId) { loadList service_re
@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()中执行。但是我在文档中没有看到任何东西可以通过这样做来解决我的问题
我需要做些什么才能让它运行一次,而不让kepp在警报启动后的一段时间内反复运行
编辑:
我的闹钟是这样设置的
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);
您有一个重复警报,这意味着它将被重复触发,并在每次触发时启动服务。如果您不需要重复,请使用
AlarmManager.set()
设置一个不重复的报警。我不确定您为什么要在服务中使用AsyncTask
-AsyncTask
主要用于UI环境。另外,onStart(…)
已被弃用,您应该改用onStart命令(…)
。但是,除此之外,您还没有提供足够的信息-如果AsyncTask
正在反复运行,则表明服务正在反复启动。如果不知道“报警”是如何设置/触发的(可能还不知道您的AsyncTask
是什么样子),很难提供帮助。我希望每4天重复一次,因为您可能有一些旧的报警。运行adb shell dumpsys alarm检查已注册的内容。另外,您的setRepeating()
调用看起来是错误的:第一个参数是'triggerAtTime',第二个参数是'interval',您拥有的将在4天后触发第一个警报,之后每天重复一次。