接收器在初始运行后几秒钟触发

时间:2016-01-31 11:24:10

标签: android android-service

我有WakefulBroadcastReceiver

public class UpdateAlarmReceiver extends WakefulBroadcastReceiver {
    private AlarmManager alarmMgr;
    private PendingIntent alarmIntent;

    @Override
    public void onReceive(Context context, Intent intent) {
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE );
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.isConnectedOrConnecting()) {
            Intent service = new Intent(context, UpdateSchedulingService.class);
            startWakefulService(context, service);
        }
    }

    public void setAlarm(Context context) {
        alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, UpdateAlarmReceiver.class);
        alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

        final Random r = new Random();
        final int hour = r.nextInt(24-9) + 9;
        final int minute = r.nextInt(60-1) + 1;
        final int second = r.nextInt(60-1) + 1;
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        //calendar.set(Calendar.SECOND, second);

        Toast.makeText(context,"Freq set to: "+Integer.toString(hour)+":"+Integer.toString(minute)+":"+Integer.toString(second),Toast.LENGTH_SHORT).show();
        alarmMgr.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_HALF_DAY, alarmIntent);

        ComponentName receiver = new ComponentName(context, UpdateBootReceiver.class);
        PackageManager pm = context.getPackageManager();

        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
    }

当我第一次运行应用程序时,我正在调用setAlarm()方法并默认激活警报管理器。但是在初始应用程序运行之后,接收器onReceive在几秒钟后被触发,即使初始时间设置为一天中的另一个时段。我无法理解为什么它被触发以及如何避免它。

1 个答案:

答案 0 :(得分:0)

如果您过去设置闹钟,则会立即触发。

您使用

final Random r = new Random();
final int hour = r.nextInt(24-9) + 9;
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);

这会将日历设置为当前时间,如果

  1. 小时是在现在之前,它将是前一段时间立即触发的同一天,或
  2. 小时是现在,它将在同一天触发,到指定的时间
  3. 您应该add到日历的时间,而不是自己设置,或者计算您的计算,以消除此错误。