Using repeating Notifications using AlarmManager - java

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);
}

Related

AlarmManager doesn't seem to be working

I'm trying to schedule a method to be called using AlarmManager, but it doesn't seem to be working. I've looked at other examples and theirs isn't working for me. So I'm thinking it's something from my code. Here's the AlarmManager code:
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(SplashScreenActivity.this, KinectReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(SplashScreenActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 2);
calendar.set(Calendar.MINUTE, 25);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
And my broadcast receiver:
public class KinectReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Done", Toast.LENGTH_LONG).show();
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_stat_notify)
.setContentTitle("Kinect")
.setColor(ContextCompat.getColor(context, R.color.colorAccent))
.setWhen(System.currentTimeMillis())
.setContentText("Your Kinects and Likes have been refilled. Now get to swiping")
.setAutoCancel(true)
.setSound(uri)
.setStyle(new NotificationCompat.BigTextStyle()
.bigText("Your Kinects and Likes have been refilled. Now get to swiping"))
.setVibrate(new long[] { 100, 500, 100, 500, 100 });
Intent targetIntent = new Intent(context, MainActivity.class);
targetIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
targetIntent.putExtra("action", "main");
targetIntent.putExtra("id", "");
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
}
Neither the Toast nor the Notification show.
The AlarmManager code is in the first thing that runs in my launcher activity, in case that helps. Thanks
Please register ur receiver in manifeast file like this
In application tag
<receiver
android:name=".KinectReceiver">
Second question is how to cancel alarm
Here is ur answer
Intent myIntent = new Intent(MainActivity.this, AlarmActivity.class);
pendingIntent = PendingIntent.getActivity(CellManageAddShowActivity.this,
id, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
pendingIntent.cancel();
alarmManager.cancel(pendingIntent);
The main thing that you will need is:
1).Create pending intent with the same id and appropriate intent FLAG.
2).Cancel that pending intent.
3).Cancel the alarm using alarm manager.

Send a notification with android at an interval

I'm trying to set a notification to appear after a certain interval. I expected this to work however nothing seems to happen when running the code on my phone other than at reciever being printed to the console and I can't seem to find out why. Any help would be greatly appreciated.
Here is the code used to set the alarm.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 10);
Intent intent = new Intent(getApplicationContext(), NotificationReciever.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES, pendingIn
Here is the notification receiver class
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("at reciever");
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeatingIntent = new Intent(context, LoginActivity.class);
repeatingIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeatingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setContentTitle("Please Leave at the cage")
.setContentText("It almost 5")
.setAutoCancel(true);
notificationManager.notify(100, builder.build());
}
}
Here are the relevant manifest lines
receiver android:name=".NotificationReciever"
uses-permission android:name="com.android.alarm.permission.SET_ALARM"
Basically you need to set a icon for each notifications.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setContentTitle("Please Leave at the cage")
.setSmallIcon(R.drawable.crosshair); //crosshair is the icon choice in this example
.setContentText("It almost 5")
.setAutoCancel(true);

Android: How to create a reminder such as google keep reminder

I want to add a reminder to my android app such as Google Keep app reminder for notes, as you know in Gkeep you can set reminder for your notes by set date (Today,Tomorrow,Next same day or Pick a date from Calendar) and set time (Morning, Afternoon,Evening, Night or pick a time from Clock).
Any help?
I found my answer! and share it with you because i think its nothing to do with Mechanical Turk :)).
in MainActivity:
final AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
final Intent intentAlarm = new Intent(MainActivity.this, AlarmReceiver.class);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 22);
calendar.set(Calendar.HOUR, 5);
calendar.set(Calendar.AM_PM, Calendar.PM);
calendar.set(Calendar.MONTH, 0);
calendar.set(Calendar.DAY_OF_MONTH, 6);
calendar.set(Calendar.YEAR,2015);
long when = calendar.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP,when, PendingIntent.getBroadcast(MainActivity.this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
and the AlarmReciver class :
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Calendar now = GregorianCalendar.getInstance();
Notification.Builder mBuilder =
new Notification.Builder(context)
.setSound(android.provider.Settings.System.DEFAULT_NOTIFICATION_URI)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("my title")
.setContentText("my text");
Intent resultIntent = new Intent(context, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
And to cancel the reminder :
if (alarmManager!= null) {
alarmManager.cancel(PendingIntent.getBroadcast(MainActivity.this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
}

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

Categories

Resources