AlarmManager不在M设备上触发

时间:2017-08-07 20:42:16

标签: java android alarmmanager

我正在开展跟踪服务。每当工人按下"签到"时,服务将开始在后台运行,每小时占用一次用户的位置。它将停止,直到用户按下"退房"或工作日结束;我正在使用WakefulBroadcastReceiver和一个服务。

首先,在按下Check-in按钮后调用我的TrackingBroadcast:

Intent intent = new Intent(this, TrackingBroadcast.class);
intent.putExtra("id_punto", id_punto);
intent.putExtra("hora_salida", horario_salida);
sendBroadcast(intent);

然后,在我的TrackingBroadcast

public static final int BROADCAST_ID = 1000;

@Override
public void onReceive(Context ctx, Intent intent){
    int id_punto = intent.getIntExtra("id_punto", 0);
    String hora_salida = intent.getStringExtra("hora_salida");
    rescheduleAlarm(ctx, id_punto, hora_salida);
}

private void rescheduleAlarm(Context ctx, int id_punto, String hora_salida){
    Intent serviceIntent      = new Intent(ctx, TrackingService.class);
    serviceIntent.putExtra("id_punto", id_punto);
    serviceIntent.putExtra("horario_salida", hora_salida);
    serviceIntent.putExtra("service_id", BROADCAST_ID);

    // Empezamos servicio, manteniendo el teléfono despierto mientras se llama
    startWakefulService(ctx, serviceIntent);
}

最后,在我的TrackingService中,我重新安排了我的TrackingBroadcast。每次更改位置时都会调用此方法,以便我可以获取最新用户的位置(我使用 FusedLocationApi

private void rescheduleAlarm(){
    long startTime, repeatingTime;

    Intent intent = new Intent(this, TrackingBroadcast.class);
    intent.putExtra("id_punto", id_punto);
    intent.putExtra("hora_salida", hora_salida);

    Calendar cal  = Calendar.getInstance();
    startTime     = cal.getTimeInMillis();
    repeatingTime = 1000 * 60 * 60 ; // Una hora

    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, BROADCAST_ID, intent, PendingIntent.FLAG_CANCEL_CURRENT);

    // Si versión del SO es > a Marshmallow, permetirá despertar teléfono incluso si está IDLE mode
    if (Build.VERSION.SDK_INT >= 23) {
        Log.d("TAG", "Alarma activada para SDK >= 23");
        alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP,
                startTime + repeatingTime,
                pendingIntent
        );
    } else {
        // Si es Lollipop, activadrá la alarma normal
        Log.d("TAG", "Alarma activada para SDK < 23");
        alarmManager.setExact(
                AlarmManager.RTC_WAKEUP,
                startTime + repeatingTime,
                pendingIntent
        );
    }

    TrackingBroadcast.completeWakefulIntent(broadcastIntent);
}

这在Lollipop设备上运行良好,它也在使用我的Nexus 6P与Android O Dev Prev 4 ...

我不知道发生了什么,因为如果我的应用正在使用Android O的DOZE模式,为什么不使用Android M设备?

谢谢!

0 个答案:

没有答案