Created
March 2, 2016 16:09
-
-
Save AlexGladkov/bd5b6f89259c5d870fcd to your computer and use it in GitHub Desktop.
Android Alarm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AlarmBroadcast extends BroadcastReceiver { | |
final public static String ONE_TIME = "onetime"; | |
//При получении сигнала о срабатывании уведомления | |
@Override | |
public void onReceive(Context context, Intent intent) { | |
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE); //Получаем соответствующий сервис | |
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Ваше сообщение в уведомлении"); // Создаем уведомление | |
//Блокируем поток | |
wl.acquire(); | |
//Здесь можно делать обработку. | |
Bundle extras= intent.getExtras(); | |
StringBuilder msgStr=new StringBuilder(); | |
if(extras!=null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){ | |
//проверяем параметр ONE_TIME, если это одиночный будильник, | |
//выводим соответствующее сообщение. | |
msgStr.append("Одноразовый будильник: "); | |
} | |
//Добавляем дату и время срабатывания | |
Format formatter=new SimpleDateFormat("hh:mm:ss a"); | |
msgStr.append(formatter.format(new Date())); | |
//Создаем события, устанавливаем флаги (сброс уведомления, уведомление стирается при нажатии) | |
Intent notificationIntent = new Intent(context, MainActivity.class); | |
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); | |
PendingIntent int1 = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); | |
//Создаем уведомление, которое появится при срабатывании даты | |
NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); | |
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context) | |
.setContentTitle("Напоминание") | |
.setContentText("Текст вашего напоминания") | |
.setSmallIcon(R.drawable.ic_launcher) | |
.setContentIntent(int1) | |
.setAutoCancel(true); // Важный параметр указывает, что нужно очистить уведомление при нажатии | |
mBuilder.build().flags |= Notification.FLAG_AUTO_CANCEL; | |
nm.notify(1, mBuilder.build()); | |
//Устанавливаем звук уведомления | |
Uri nt = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); | |
Ringtone r = RingtoneManager.getRingtone(context, nt); | |
r.play(); | |
//Разблокируем поток. | |
wl.release(); | |
} | |
public void SetAlarm(Context context, String inputString, int id) | |
{ | |
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); | |
Intent intent = new Intent(context, AlarmBroadcast.class); | |
intent.putExtra(ONE_TIME, Boolean.FALSE); //Параметр интента | |
PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, 0); | |
//Интервал срабатывания 5 секунд | |
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |
SimpleDateFormat anothersdf = new SimpleDateFormat("yyyy-MM-dd"); | |
sdf.setTimeZone(TimeZone.getDefault()); | |
//Здесь делаем так, чтоб уведомление не появлялось, если время срабатывания уже прошло, а именно переносим на следующий день | |
Date date = new Date(); | |
String data = anothersdf.format(date) + " " + inputString; | |
Date current = date; | |
try { | |
date = sdf.parse(data); | |
} catch (ParseException e) { | |
} | |
Calendar c = Calendar.getInstance(); | |
c.setTime(date); | |
if (date.compareTo(current)<0) { | |
c.add(Calendar.DATE, 1); | |
} | |
date = c.getTime(); | |
am.setRepeating(AlarmManager.RTC_WAKEUP, date.getTime(), AlarmManager.INTERVAL_DAY, pi); | |
} | |
public void CancelAlarm(Context context) { | |
Intent intent = new Intent(context, AlarmBroadcast.class); | |
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); | |
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); | |
alarmManager.cancel(sender); //Отменяем будильник связанный с интентом данного класс | |
} | |
public void setOneTimeTimer(Context context, String inputString, int id) { | |
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); | |
Intent intent = new Intent(context, AlarmBroadcast.class); | |
intent.putExtra(ONE_TIME, Boolean.TRUE); | |
PendingIntent pi = PendingIntent.getBroadcast(context, id, intent, 0); | |
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); | |
SimpleDateFormat anothersdf = new SimpleDateFormat("yyyy-MM-dd"); | |
sdf.setTimeZone(TimeZone.getDefault()); | |
Date date = new Date(); | |
String data = anothersdf.format(date) + " " + inputString; | |
try { | |
date = sdf.parse(data); | |
} catch (ParseException e) { | |
} | |
am.set(AlarmManager.RTC_WAKEUP, date.getTime(), pi); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Создание и вызов будильника | |
AlarmBroadcast alarm = new AlarmBroadcast(); | |
alarm.SetAlarm(getApplicationContext(), time, notid); // time - ваше время в формате Date, notid - уникальный идентификатор будильника, нужно, чтобы делать несколько будильников |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment