android - AlarmManager 不重复

标签 android service alarmmanager android-alarms repeatingalarm

我正在编写一个“简单”通知器,它包括调用网站、检查响应并通知是否有新内容。

我正在使用一个服务来执行 http 操作,我希望 AlarmManager 以给定的频率重复调用该服务。我一直在查看像 this 这样的教程和其他示例,并且由于我希望在用户离开设置屏幕(迄今为止唯一的 Activity)和 BOOT 完成后安排服务,所以我创建了一个类来包装调度代码。

public class Scheduler {

public static boolean cancelScheduledService(Context ctx, Intent serviceIntent) {
    boolean success = true;
    Log.v("novUmbria", "Scheduler.cancelScheduledService");
    try {
        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
        am.cancel(
                PendingIntent.getBroadcast(
                        ctx, 0,
                        new Intent(ctx, NotificadorService.class),
                        // si ya existe, no genera un 2º
                        PendingIntent.FLAG_CANCEL_CURRENT
                        )

                );
        Log.v("novUmbria", "Scheduler.cancelScheduledService Servicio cancelado");
    } catch (Exception e) {
        Log.e("novUmbria", "Scheduler.cancelScheduledService Excepción: " + e.getMessage());
        success = false;
    }
    return success;
}

public static boolean scheduleService(Context ctx, Intent serviceIntent, long interval) {
    boolean success = true;
    Log.v("novUmbria", "Scheduler.scheduleService Servicio ");
    try {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm");
        // timeformat.setTimeZone(TimeZone.getTimeZone("Europe/Madrid"));

        AlarmManager am = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
        am.setRepeating(
                // am.setInexactRepeating(
                // AlarmManager.ELAPSED_REALTIME_WAKEUP,
                AlarmManager.RTC_WAKEUP,
                cal.getTimeInMillis(),
                interval,
                PendingIntent.getBroadcast(
                        ctx, 0,
                        new Intent(ctx, NotificadorService.class),
                        // si ya existe, no genera un 2º
                        PendingIntent.FLAG_CANCEL_CURRENT
                        )

                );
        Log.v("novUmbria", "Scheduler.scheduleService Servicio programado a las "
                + timeformat.format(cal.getTime())
                + " cada " + (interval / 60000) + " minutos"
                );

        startService(ctx, serviceIntent);
        Log.v("novUmbria", "Scheduler.scheduleService Servicio iniciado"
                );

    } catch (Exception e) {
        Log.e("novUmbria", "Scheduler.scheduleService Excepción: " + e.getMessage());
        success = false;
    }
    return success;
}

public static boolean startService(Context ctx, Intent serviceIntent) {
    boolean success = true;
    Log.v("novUmbria", "Scheduler.startService");
    try {
        ctx.startService(serviceIntent);
        Log.v("novUmbria", "Scheduler.startService Servicio iniciado");
    } catch (Exception e) {
        Log.e("novUmbria", "Scheduler.startService Excepción: " + e.getMessage());
        success = false;
    }
    return success;
}

这是从设置 Activity 调用调度程序

//Settings Activity
 @Override
protected void onStop() {
    Log.v("novUmbria", "SettingsActivity.onStop");
    Intent serviceIntent = new Intent(getApplicationContext(), NotificadorService.class);
    Scheduler.cancelScheduledService(getApplicationContext(), serviceIntent);
    long frequency = 1000 * 60 / 2;
    Scheduler.scheduleService(getApplicationContext(),
            serviceIntent,
            frequency
            );
    Log.v("novUmbria", "SettingsActivity.onStop scheduleService");
    super.onStop();
}

事情是:logcat 告诉我服务已安排(或者,更好地说,它不会引发异常)并且它是第一次执行。但是,在那之后,无论间隔多长或多短,都不再重复。我已经尝试了几个标志 RTC、RTC_WAKEUP、ELAPSED_REALTIME 等,但我一无所获。

我的测试设备是完全更新的 Nexus 4。我什至重新启动了它,所以我检查了 BOOT_COMPLETE 接收器工作正常,但它从不重复服务调用。

关于问题出在哪里的任何想法?

提前致谢。

最佳答案

我找到了答案 here .

显然,当您想要安排服务时,您不会使用 PendingIntent.getBroadcast,而是使用 PendingIntent.getService

只是那个小小的变化,它会按预期重复。<​​/p>

希望这对其他人有帮助:)

关于android - AlarmManager 不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18576953/

相关文章:

android - android.location.geocoder 的问题

node.js - Node 、要求、单例还是非单例?

android - 是否可以从对话框中调用 onReceive 方法?

android - 更新应用程序是否会清除共享首选项或删除应用程序设置的警报?

Android:防止在平板电脑上安装

java - 使用并行线程进行不同的网络操作

android - 带有 ADT 的 Eclipse - adb.exe 即使在 IDE 退出后仍继续运行

java - 新的 Intent (上下文,类)抛出 NullPointerException

python - 使用 Python 进行 GPG 解密(作为 Windows 服务)

android - 将新 Intent 发送到广播接收器会提供先前 Intent 的额外值