报警管理器不工作

时间:2013-04-18 07:31:21

标签: android alarmmanager

我正在尝试为我的应用创建一个新的调度程序,每天在用户定义的时间运行。这是下面的代码。问题是调度程序没有在设定的时间运行。请建议如何执行此操作

 private void setAlarm(String targetCal){
    Toast.makeText(MainActivity.this,"Alarm Set", Toast.LENGTH_LONG).show();
    String[] Time=targetCal.split(":");
    Calendar timeOff = Calendar.getInstance();
    Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
    AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);

    //int days = Calendar.SUNDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how many days until Sunday
    timeOff.set(Calendar.HOUR,Integer.valueOf(Time[0].trim()));
    timeOff.set(Calendar.MINUTE,Integer.valueOf(Time[1].trim()));
    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(), alarmManager.INTERVAL_DAY , pendingIntent);

}

2 个答案:

答案 0 :(得分:2)

试试此代码

    Intent i = new Intent("in.servicealarmdemo.demoactivity");

/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), count+2, i, Intent.FLAG_ACTIVITY_NEW_TASK);

/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
/** Creating a calendar object corresponding to the date and time set by the user */
GregorianCalendar calendar = new GregorianCalendar(pYear,pMonth,pDay,pHour,pMinute);

/** Converting the date and time in to milliseconds elapsed since epoch */
long alarm_time = calendar.getTimeInMillis();

/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.RTC_WAKEUP  , alarm_time , operation);

/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();

或者您可以简单地尝试本教程

http://wptrafficanalyzer.in/blog/setting-up-alarm-using-alarmmanager-and-waking-up-screen-and-unlocking-keypad-on-alarm-goes-off-in-android/

答案 1 :(得分:0)

通过设置变量可能会出现问题。而是尝试找出当前时间和新值之间的差异,然后执行:

timeOff.add(Calender.HOUR,diff);