我的应用正在执行人员活动识别,并通知用户他们是否不够活跃。我正在一个正在运行的前台服务中读取加速度计的数据。目前我正在尝试在用户休眠时启动和停止服务(例如,用户将睡眠时间间隔设置为晚上8点 - 早上8点),因此应该停止服务并在指定时间后重新开始服务。目前,以下代码不起作用,我不知道为什么。有什么建议吗?
注意:我知道,我将以某种方式使代码重用Calendar实例,这仅用于调试目的并使其首先运行。
Date startSleepingHours = mUser.getStartSleepingHours();
Date stopSleepingHours = mUser.getStopSleepingHours();
//Create alarm manager
AlarmManager alarmMgr0 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, startSleepingHours.getHours());
cal.set(Calendar.MINUTE, startSleepingHours.getMinutes());
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
Intent startServiceIntent = new Intent(ActiveMinutesActivity.this, IntentBroadcastedReceiver.class);
Intent stopServiceIntent = new Intent(ActiveMinutesActivity.this, IntentBroadcastedReceiver.class);
stopServiceIntent.putExtra("command", "STOP_SERVICE");
PendingIntent stopServicePIntent = PendingIntent.getService(ActiveMinutesActivity.this, 0, stopServiceIntent, 0);
PendingIntent startServicePIntent = PendingIntent.getService(ActiveMinutesActivity.this, 1, startServiceIntent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60 * 1000, stopServicePIntent);
Calendar cal2 = new GregorianCalendar();
cal2.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal2.set(Calendar.HOUR_OF_DAY, stopSleepingHours.getHours());
cal2.set(Calendar.MINUTE, stopSleepingHours.getMinutes());
cal2.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal2.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal2.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal2.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal2.getTimeInMillis(), 60 * 1000, startServicePIntent);
我的Receiver课程:
public class IntentBroadcastedReceiver extends BroadcastReceiver {
public IntentBroadcastedReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null){
if(intent.getExtras().get("command").equals("STOP_SERVICE")){
context.stopService(new Intent(context, ActiveMinutesService.class));
}else {
context.startService(new Intent(context, ActiveMinutesService.class));
}
}
}
}
答案 0 :(得分:0)
您是否已将IntentBroadcastedReceiver定义为AndroidManifest.xml中的接收器?即:
<receiver android:name=".IntentBroadcastedReceiver "></receiver>