1

Не правильно по времени срабатывает AlarmManager. Подскажите в чем ошибка, пожалуйста.

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.icu.util.Calendar;
import android.os.Build;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;

import com.example.yass.remindme.MainActivity;
import com.example.yass.remindme.R;
import com.example.yass.remindme.db.SharedPreferencesHelper;
import com.example.yass.remindme.models.TimeRefresh;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by yass on 4/14/17.
 */

public class IntentServiceNotification extends IntentService {

    private static final String TAG = "IntentService";
    private static long POLL_INTERVAL = 0;

    public IntentServiceNotification() {
        super(TAG);
    }


    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        //  if (SharedPreferencesHelper.getInstance().getStatusTimeRefresh() == 1) {
        sendNotification();
        // }
    }


    public static void setServiceAlarm(Context context, boolean isOn) {
        Intent intent = new Intent(context, IntentServiceNotification.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 15, intent, 0);
        AlarmManager alarmManager = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);

        POLL_INTERVAL = getPollInterval();

        TimeRefresh timeRefresh = SharedPreferencesHelper.getInstance().getTimeRefresh();

        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(java.util.Calendar.HOUR_OF_DAY, timeRefresh.getHourDate());
        calendar.set(java.util.Calendar.MINUTE, timeRefresh.getMinutesDate());

        if (isOn) {

            alarmManager.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), calendar.getTimeInMillis(), pendingIntent);
        } else {
            alarmManager.cancel(pendingIntent);
            pendingIntent.cancel();
        }
    }

    public static long getPollInterval() {

        TimeRefresh timeRefresh = SharedPreferencesHelper.getInstance().getTimeRefresh();
        int[] days = timeRefresh.getDayOfWeek();

        int currentTimeMillis = (timeRefresh.getHourDate() * 3600000 )+ (timeRefresh.getMinutesDate() * 60000);

        Log.i(TAG, "Current Millisec = " + currentTimeMillis  + " Days = " + days[0] + " "
                + days[1] + " " + days[2] + " " + days[3] + " " + days[4] + " " + days[5] + " " + days[6]);


        if ((timeRefresh.getHourDate() + timeRefresh.getMinutesDate()) > 43200000){
            return   (currentTimeMillis - (timeRefresh.getHourDate() + timeRefresh.getMinutesDate()));
        } else {
            return  ((currentTimeMillis - 86400000) + currentTimeMillis + timeRefresh.getHourDate() + timeRefresh.getMinutesDate());
        }
    }

    private void sendNotification() {
        Notification.Builder builder = new Notification.Builder(this);
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,
                0, intent, PendingIntent.FLAG_CANCEL_CURRENT);

        builder.setContentIntent(pendingIntent)
                .setSmallIcon(R.drawable.alarm_clock)
                .setContentTitle("Remind !!!")
                .setContentText("Time to go");
        Notification notification = builder.build();
        NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(this);
        notificationManagerCompat.notify(16, notification);
    }
}

2 ответа 2

2

Проблема AlarmManager в том, что он НЕ гарантирует точного срабатывания в назначенное время. На официальном сайте Android'a об этом написано - Alarm Manager

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.


Так же в документации, на строчку выше, пишется:

Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time, even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier and much more efficient to use Handler.

Если вкратце, то Вам говорят: - "Для точных операций используйте Handler". P.S. Handler

7
  • Что посоветуете вместо AlarmManager использовать для написания пиложения "Будильник" ?
    – IgorDenis
    16 апр 2017 в 15:50
  • @IgorDenis, документацию читайте... Так для Вас же быстрее. Я обновил вопрос. 16 апр 2017 в 15:58
  • @IgorDenis, если ответ помог Вам, примите его. 16 апр 2017 в 16:14
  • @RostislavDugin, кажется у вас всё равно в ответе не указано что использовать для приложения-будильника)
    – ЮрийСПб
    16 апр 2017 в 16:38
  • 1
    @RostislavDugin, ну вот я не уверен, что сказав handler выполниться через 5 минут и смахнув приложение он таки выполнится) А вот AlarmManager пусть не точно, но выполнится
    – ЮрийСПб
    16 апр 2017 в 16:48
0

Неправильно по времени срабатывает, потому что вы используете флаг AlarmManager.RTC.

Если устройство спит, то напоминание может быть отложено на неопределенное время. Например до времени следующего напоминания, которое должно будет его разбудить. Ради экономии аккумулятора.

Чтобы AlarmManager срабатывал в назначенное время, используйте флаг AlarmManager.RTC_WAKEUP.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.