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);
}
}
Проблема 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
Современные инструменты для криптотрейдинга: как технологии помогают принимать решения
Апостиль в Лос-Анджелесе без лишних нервов и бумажной волокиты
Основные этапы разработки сайта для стоматологической клиники
Продвижение своими сайтами как стратегия роста и независимости