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

227
18 апреля 2017, 07:53
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);
    }
}
Answer 1

Проблема 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

READ ALSO
Встраивание API в андроид приложение [требует правки]

Встраивание API в андроид приложение [требует правки]

Нужно встроить api яндекс переводчика в мобильное приложение, на андроид начал программировать недавно, с API до этого не работал, поэтому уперся...

229
Помогите, не понимаю как использовать return в java

Помогите, не понимаю как использовать return в java

Вот вроде понимаю что return что-то возвращает, завершает процессы метода(функции), но что, как он это делает вообще не понимаюПересмотрел кучу...

279
Для чего необходимо вводить аннотацию @Entity при определение класса , Hibernate

Для чего необходимо вводить аннотацию @Entity при определение класса , Hibernate

Не совсем ясно в чем смысл этой аннотации когда есть @Table которая явно указывает с какой таблицей идет связь

209