我正在尝试在BroadcastReceiver
的帮助下以特定的时间间隔启动服务。我已经将接收器定义为服务中的内部类,如下所示:
public class AlarmReciever extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("RTESPLDebug", "Recieved Broadcast!"); //Never appears in LogCat
//Intent i = new Intent(context, LocationUpdateService.class);
context.startService(intent);
}
};
我在服务的onCreate()
注册闹钟接收器:
context = super.getApplicationContext();
AlarmReceiver ar = new AlarmReceiver();
IntentFilter intfilter = new IntentFilter(Intent.ACTION_DEFAULT);
intfilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(ar, intfilter);
我首先从第一个活动开始服务,然后在那里注册一个警报:
Intent i = new Intent(context, LocationUpdateService.class);
context.startService(i);
// Schedule first alarm
int nextUpdateInterval = 30*1000; // Let first alarm be after 30 sec
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, LocationUpdateService.class);
intent.setAction(Intent.ACTION_DEFAULT);
intent.addCategory(Intent.CATEGORY_DEFAULT);
PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+nextUpdateInterval, pintent);
在服务中我注册了单个位置更新,当我收到更新(我收到)时,我处理它(我已经调试了这个,处理确实完成而没有错误),然后我以类似的方式注册下一个警报如上所述:
int nextUpdateInterval = getNextUpdateInterval(); // Returns 30000
Calendar cal = Calendar.getInstance();
Intent intent = new Intent(context, LocationUpdateService.class);
intent.setAction(Intent.ACTION_DEFAULT);
intent.addCategory(Intent.CATEGORY_DEFAULT);
PendingIntent pintent = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()+nextUpdateInterval, pintent);
很多代码和很长的问题。