在每天的特定时间设置启动时间的警报

Dee*_*lra 2 android broadcastreceiver alarmmanager repeatingalarm

我已经在启动完成时在android上启动了9:00 AM的警报.但是在完成启动后每分钟都会发出警报.

我的要求是它应该在启动后设置警报,但仅在上午9:00触发警报.

这是我的代码:public class AlarmUtil {private PendingIntent alarmIntent;

public static void setAlarm(Context context) {

    AlarmManager alarmManager = (AlarmManager) context
            .getSystemService(Context.ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 9);
    calendar.set(Calendar.MINUTE, 00);
    calendar.set(Calendar.SECOND, 00);
    calendar.set(Calendar.AM_PM, Calendar.AM);
    //calendar.setTimeInMillis(calendar.getTimeInMillis());
    calendar.add(Calendar.SECOND, 1);

    Intent intent = new Intent(context, Services.class);
    PendingIntent pintent = PendingIntent.getService(context, 123456789,
            intent, 0);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);

}
}

public class AlarmBroadcastReciever extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
        Toast.makeText(context, "Booted!", Toast.LENGTH_SHORT).show();
        AlarmUtil.setAlarm(context);

    }
}
}
Run Code Online (Sandbox Code Playgroud)

服务(我的服务类)

public class Services extends IntentService {

public Services(String name) {
    super("services");
    // TODO Auto-generated constructor stub
}

public Services() {
    super("services");
    // TODO Auto-generated constructor stub
}

@Override
public void onCreate() {
    super.onCreate();

}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    MyApp.counter += 1;

    Toast.makeText(getApplicationContext(),
            "Service started: " + MyApp.counter, Toast.LENGTH_LONG).show();
    return START_STICKY;
}

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}

@Override
protected void onHandleIntent(Intent intent) {
    Toast.makeText(getApplicationContext(), "handling intent",
            Toast.LENGTH_LONG).show();

}
Run Code Online (Sandbox Code Playgroud)

}

我缺乏的地方.请帮我.提前致谢.

mat*_*ash 5

alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
        calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);
Run Code Online (Sandbox Code Playgroud)

通过呼叫setRepeating(),你指示它在每一分钟发出意图.你可能想要使用set()setExact()代替.

此外,您将在当前日期的 9:00设置闹钟.我不确定你的目标是什么,但是如果你想要"下一个9点"(即作为闹钟)的警报,如果当前时间大于9:00,你应该增加一天.从文档:

如果指定的触发时间是过去的,则会立即触发警报.

编辑:如果您需要的是每天9点发出此警报,那么setRepeating()是正确的,但是以毫秒为单位的时间应该是AlarmManager.INTERVAL_DAY.但请注意有关过去警报的说明.如果您在上午10:00启动手机,并且使用当前代码,除了未来的代码之外,您将立即收到警报.

并且,正如@DerGolem指出的那样,如果您将API级别19定位,那么这些警报将是不精确的(并且没有setRepeatingExact()).如果你需要精确的警报,那么你必须安排一个警报,然后安排下一个警报,setExact()等等.