AlarmManager schedule android java - java

I have some schedule in my app, and i need to do some task in specific time every day(in other time) example at 7:00 in Monday , at 12:00 in Tuesday etc. And schedule in others weeks of month can be different. How can i do this.

I think this will help you figure how to setup events happening at certain times and how to interact with them programmatically.
The main premise is that you use an AlarmManager to schedule your events:
Calendar cal = Calendar.getInstance();
Intent activate = new Intent(context, Alarm.class);
AlarmManager alarms ;
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, activate, 0);
alarms = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
cal.set(Calendar.HOUR_OF_DAY, hour);
cal.set(Calendar.MINUTE, minute);
cal.set(Calendar.SECOND, 00);
alarms.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), alarmIntent);
and you use a BroadcastReceiver to add functionality when that time is reached:
public class Alarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
MediaPlayer mp = MediaPlayer.create(context, R.raw.ferry_sound);
mp.start();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "My Tag");
wl.acquire();
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
long[] s = { 0, 100, 10, 500, 10, 100, 0, 500, 10, 100, 10, 500 };
vibrator.vibrate(s, -1);
}
}
You'll need to register your receiver in your manifest.xml
<Application ... >
...
<receiver android:process=":remote" android:name="Alarm" />
...
</Application>

Related

Using repeating Notifications using AlarmManager

I'm trying to develop an app which requires scheduled notifications everyday at 7am, 11am and 7pm. And when user taps on the notification it takes the user to MainActivity.
I have a working code but it's showing random behavior. I have the following problems.
1) Every time I open MainActivity, it triggers the alarm manager and shows a notification even though it's only supposed to be triggered at 7am, 11am and 7pm.
2) Also, I think I'm somehow duplicating alarms every time I open the main activity. Everytime I setup the alarm, I cancel the pending intent and then setup again. Is this the correct way to do it?
Manifest.xml
<receiver android:name=".AlarmReceiver">
<intent-filter>
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
MainActivity.java
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar cal = Calendar.getInstance();
Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, 0);
PendingIntent broadcast1 = PendingIntent.getBroadcast(this, 101, notificationIntent, 0);
PendingIntent broadcast2 = PendingIntent.getBroadcast(this, 102, notificationIntent, 0);
cal.set(Calendar.HOUR_OF_DAY, 7);
cal.set(Calendar.MINUTE, 0);
alarmManager.cancel(broadcast);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, broadcast);
cal1.set(Calendar.HOUR_OF_DAY, 11);
cal1.set(Calendar.MINUTE, 0);
alarmManager.cancel(broadcast1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, broadcast1);
cal2.set(Calendar.HOUR_OF_DAY, 19);
cal2.set(Calendar.MINUTE, 0);
alarmManager.cancel(broadcast2);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, broadcast2);
AlarmReceiver.java
#Override
public void onReceive(Context context, Intent intent) {
String Text = getText();
Resources res = context.getResources();
Intent notificationIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setSmallIcon(R.drawable.ic_menu_notify)
.setTicker("Ticker")
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setContentTitle("Title")
.setContentText(Text)
.setAutoCancel(true)
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}

AlarmManager Set Specific Time Execution

I was having some problem when trying to set specific time to execute the AlarmManager. Here is the code where I schedule my Alarm:
public static void scheduleAlarms(Context context) {
Calendar cur_cal = new GregorianCalendar();
cur_cal.setTimeInMillis(System.currentTimeMillis());//set the current time and date for this calendar
Calendar cal = new GregorianCalendar();
cal.add(Calendar.DAY_OF_YEAR, cur_cal.get(Calendar.DAY_OF_YEAR));
cal.set(Calendar.HOUR_OF_DAY, 00);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, cur_cal.get(Calendar.SECOND));
cal.set(Calendar.MILLISECOND, cur_cal.get(Calendar.MILLISECOND));
cal.set(Calendar.DATE, cur_cal.get(Calendar.DATE));
cal.set(Calendar.MONTH, cur_cal.get(Calendar.MONTH));
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context, Alarm.class);
notificationCount = notificationCount + 1;
notificationIntent.putExtra("NotifyCount", notificationCount);
PendingIntent pi = PendingIntent.getBroadcast(context, 1,
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mgr.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pi);
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
}
I am trying to set the alarm manager to run at 0030 if it meets the conditions in my if statement. However, the alarmManager will not send push-notification although some records did met the requirements. So I changed the codes to repeat every 2 minutes by:
mgr.setRepeating(AlarmManager.RTC_WAKEUP, System.getTimeInMillis(),
2*60*60, pi);
And it did send the push-notifications correctly. I wonder what's the mistake I made for the part when I tried to specified a time for it to execute.
Thanks in advance.

Alarm Manager fail to setRepeating

I am having some problem with Alarm Manager in Android.
Inside the onCreate method:
notificationCount = notificationCount + 1;
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context,
ReminderAlarm.class);
notificationIntent.putExtra("NotifyCount", notificationCount);
PendingIntent pi = PendingIntent.getBroadcast(context,
notificationCount, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
60000+System.currentTimeMillis(), pi);
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Reminder Alarm class:
public class ReminderAlarm extends BroadcastReceiver {
private NotificationManager mNotificationManager;
private Notification notification;
#Override
public void onReceive(Context context, Intent intent) {
mNotificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
PendingIntent contentIntent = PendingIntent
.getActivity(context, 0, new Intent(), 0);
notification = new Notification(
R.drawable.ic_launcher, "Notification",
System.currentTimeMillis());
notification
.setLatestEventInfo(context, "AlarmActivated", "Hello", contentIntent);
mNotificationManager.notify(
Integer.parseInt(intent.getExtras()
.get("NotifyCount").toString()),
notification); }}
In the boot receiver class:
public void onReceive(Context context, Intent i) {
scheduleAlarms(context);
}
static void scheduleAlarms(Context context) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 1);
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context, ReminderAlarm.class);
PendingIntent pi = PendingIntent.getService(context, 0,
notificationIntent, 0);
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),
60000+System.currentTimeMillis(),
pi);
}
And in my manifest file:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".ReminderAlarm" >
</receiver>
<receiver
android:name=".BootReceiver"
android:enabled="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" >
</action>
</intent-filter>
</receiver>
I am trying to set the alarm to repeat every minute and prompt user notification. But it works in this way: when I launch the apps, it sets the alarm for once. After it prompt notification for once, then it stopped the repeating for every minute.
I wonder which part of my code went wrong. Thanks in advance.
EDIT
So basically I want the alarm manager to repeat everyday at 12am. Here is the codes:
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0 );
calendar.set(Calendar.MINUTE, 1);
notificationCount = notificationCount + 1;
AlarmManager mgr = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent(context,
ReminderAlarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context,
notificationCount, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
mgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
ComponentName receiver = new ComponentName(context, BootReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
So by setting the repeating as such, will it still run after 44 years as previous one? or it will repeat everyday at 12am?
The third parameter in the setInexactRepeating() method is the interval in milliseconds. You're setting that as the number of milliseconds that have elapsed since January 1, 1970 00:00:00.0 UTC plus 60000, making the next scheduled event about 44 years in the future. Change your code as follows:
mgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 60000, pi);

How to create a notification service?

Sorry if any of this kind of question has already been posted, i still didnt find the answer that I'm looking for.
My mission is simple - I want to create an app that pushes a notification excatly in 9PM.
Here's what I found and what I currently have -
Intent intent = new Intent();
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 6);
cal.set(Calendar.HOUR, 9);
cal.set(Calendar.AM_PM, Calendar.PM);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24 , pIntent);
Notification noti = new Notification.Builder(this)
.setTicker("Ticker Title")
.setContentTitle("Content Title")
.setContentText("Notification content.")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(pIntent).getNotification();
noti.flags=Notification.FLAG_AUTO_CANCEL;
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, noti);
I herd there has to be a kind of service to display the notification. How do I create it? If my code's wrong, feel free to re-make it.
Thanks a lot in advance!!
inside manifest
<service android:enabled="true" android:name=".NotifyIntentService" />
<receiver android:name=".AlarmReciever"/>
inside Activity
Intent intent = new Intent(this, AlarmReciever.class);
AlarmManager alarm = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
Calendar cal = Calendar.getInstance();
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MINUTE, 6);
cal.set(Calendar.HOUR, 9);
cal.set(Calendar.AM_PM, Calendar.PM);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pIntent);
inside main project
public class AlarmReciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
Intent serviceIntent = new Intent(context,
NotifyIntentService.class);
startService(serviceIntent);
}
}
intent service
public class NotifyIntentService extends IntentService
{
#Override
protected void onHandleIntent(Intent intent) {
//your notification code
//notify();
}
}
notification in all device

Setting a repeating alarm in android

I am trying to set a repeating alarm in android that eventually will go up at a user specified time. However the alarm goes off right away when once it is set, even when I make sure the alarm isn't set to go off until after the alarm has been set. For example, I have the code below set to have an alarm go off at 10:43 so I set the alarm at 10:41, but the alarm goes off right away. Any ideas? Thanks in advance.
public class Alarm extends BroadcastReceiver {
#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();
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For
Intent scheduledIntent = new Intent(context,ReminderMessage.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);
// example
wl.release();
}
public void SetAlarm(Context context) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Date dat = new Date();
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY, 10);
cal_alarm.set(Calendar.MINUTE, 43);
cal_alarm.set(Calendar.SECOND, 0);
if(cal_alarm.before(cal_now)){
cal_alarm.add(Calendar.DATE, 1);
}
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context) {
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent
.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
I think your line:
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), cal_alarm.getTimeInMillis() , pi); // Millisec * Second * Minute
is triggering the alarm immediately, the second param is the scheduled time, and the third is the period. So if you wanted your alarm to go off at cal_alarm time, you want to use something like:
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(), 1000*60*5 , pi); // Millisec * Second * Minute
That should go off at the cal_alarm time, and repeat every 5 mins.
AlarmManager.SetRepeating API Doc

Categories

Resources