I have added everything like adding a receiver in the manifest file, adding all permissions still I am not able to call notifications. I want to give a fixed times, Example Daily morning 8:00 am, 12:00 am,9:00 pm I want to show notifications, how to do that? please help me.
Manifest permissions
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
Receiver
<receiver android:name=".Activity.Utils.AlertReceiver"> </receiver>
alert receiver class
public class AlertReceiver extends BroadcastReceiver {
NotificationManager notificationManager ;
boolean isNotificActive = false ;
int id =1;
#Override
public void onReceive(Context context, Intent intent) {
long when = System.currentTimeMillis();
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, DashBoard.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 100,notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.logo_medi)
.setContentTitle("Alarm Fired")
.setContentText("Events To be PErformed").setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
notificationManager.notify(100, mNotifyBuilder.build());
id++;
System.out.println("notification is calling ");
}
setting alarm from an adapter class
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
calendar.set(Calendar.SECOND, 10);
Intent intent1 = new Intent(context, DashBoard.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 100,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);
Related
I have tried many solutions from stackoverflow but none of them worked...I want to set the repeating alarm to get notified for pending bills...
so far i have tried this,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pending_sales_purchase);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Calendar cal=Calendar.getInstance();
cal.set(Calendar.MONTH,5);
cal.set(Calendar.YEAR,2018);
cal.set(Calendar.DAY_OF_MONTH,8);
cal.set(Calendar.HOUR_OF_DAY,15);
cal.set(Calendar.MINUTE,35);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 1253, intent, PendingIntent.FLAG_UPDATE_CURRENT| Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),pendingIntent );
Toast.makeText(this, "Alarm worked.", Toast.LENGTH_LONG).show();
}
MyBroadcastReceiver class
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked1111.", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = "dddd";
String description = "aaaa";
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("a", name, importance);
channel.setDescription(description);
NotificationManager notificationManager =context.getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
intent = new Intent(context, PendingSalesPurchaseActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, "a")
.setSmallIcon(R.drawable.ic_search_commit)
.setContentTitle("My notification")
.setContentText("Hello World!")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
}
Add below code to set notification.
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
For repeating alarm everyday, You need to use setRepeating().
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent );
Of, if you don't require repeating alarm on exact time then it's better to use setInexactRepeating()
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent );
Schedule a repeating alarm that has inexact trigger time requirements;
for example, an alarm that repeats every hour, but not necessarily at
the top of every hour. These alarms are more power-efficient than the
strict recurrences traditionally supplied by setRepeating(int, long,
long, PendingIntent), since the system can adjust alarms' delivery
times to cause them to fire simultaneously, avoiding waking the device
from sleep more than necessary.
You need to use this code for daily notification on same time.
public static void setReminder(Context context, int hour, int min)
{
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
if(setcalendar.before(calendar))
setcalendar.add(Calendar.DATE,1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, cls);//Class Name from where it trigger
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Variables in BroadcastReceiver are not updating every time i set a notification/alarm manager.
"receiver (recycler)" is from a fragment.
receiver" is from a BroadcastReceiver class.
onCreateView
intentAlarmManager = new Intent(context, NotificationReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, intentAlarmManager, PendingIntent.FLAG_UPDATE_CURRENT);
Notification Method
private void setNotification(int hour, int min, int interval, int uniqueID) {
//get instance of the calendar
calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, min);
//create delayed intent
pendingIntent = PendingIntent.getBroadcast(context, uniqueID, intentAlarmManager, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * (interval * 30), pendingIntent);
}
Recycler its attached to a switch listener
setNotification(Integer.parseInt(model.getHour()), Integer.parseInt(model.getMinute()), Integer.parseInt(model.getInterval()), Integer.parseInt(model.getTime()));
Receiver
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intentToStartWhenAlarmSets = new Intent(context, LoginActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) System.currentTimeMillis(), intentToStartWhenAlarmSets, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Content Title")
.setContentText("Notify " + HomeFragment.notifMedName)
.setSound(notifSound)
.setVibrate(pattern)
//swipable
.setAutoCancel(true);
Log.d(ContentValues.TAG, "receiver " + HomeFragment.notifMedName);
notificationManager.notify((int) System.currentTimeMillis(), builder.build());
I figured it out, i think. Although I'm not sure if this is the best/correct way (i'ts working though).
So in in my receiver class i added
intent.getStringExtra("string);
and in my fragment i added
intentAlarmManager.putExtra("string", notifMedName);
getActivity().sendBroadcast(intentAlarmManager);
and also i changed all pending intent from context to getActivity().
Feel free to answer if you guys have a better solution.
More info here.
I have a calendar library I grabbed off of github:
https://github.com/prolificinteractive/material-calendarview
And I'm having the user click on a date and add a reminder for that date, an alert dialog then pops up and asks them to enter the time they would like to be reminded on that day.
Now I was able to convert the text into a simpledate format and I spit it out into a string from a calendar object, so the date and time should be passing through the notification. But it doesn't seem to work anyways
Heres the code that sets the alarm:
Calendar cal = Calendar.getInstance();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getService(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
try {
cal.setTime(alertFormatter.parse(date));
System.out.print("Date added successfully");
} catch (ParseException e) {
System.out.println("Failed to add date");
}
cal.add(Calendar.HOUR, Integer.parseInt(hour.getText().toString()));
cal.add(Calendar.MINUTE, Integer.parseInt(minute.getText().toString()));
cal.add(Calendar.SECOND, 0);
if(spAMpm.getSelectedItem().equals("AM"))cal.add(Calendar.AM_PM, Calendar.AM);
else if (spAMpm.getSelectedItem().equals("PM"))cal.add(Calendar.AM_PM, Calendar.PM);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
Then the receiver I created to do what I need it to do:
public class UpcomingWorkNotification extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, UpcomingWork.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(UpcomingWork.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Four.oh")
.setContentText("Assignment Due Soon!")
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, builder.build());
}
}
In the manifest I gave it this permission and added the receiver
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<receiver android:name=".UpcomingWorkNotification">
<action android:name="android.media.action.DISPLAY_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</receiver>
Even with all that the notification still doesn't appear when I set it
Can anyone help?
And thank you
I try to set an alarm depending user chocies while setting alarm i want to send that alarm's unique notification id to reciever.java. I want to get data by this id on reciever.java.
I have a form with this form users are adding their pills and I'm saving every pill in different xml files for example pill1.xml pill2.xml. That saved pills have alarm and notification when alarm time came for example pill2.xml i will show pill2 datas in notirifacation bar.
that code on bottom is how i create alarm.
Long alertTime = new GregorianCalendar().getTimeInMillis()+10*1000;
Intent alertIntent = new Intent(ilac_hatirlatma.this, hatirlatma_detay.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(ilac_hatirlatma.this, NOTIF_ID, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
reciever.java
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context, "İlaç Hatırlatma", "8 saatte bir içmeniz gereken 'Arvelez' adlı ilacınız bulunmaktadır.", "İlacınzı Almayı Unutmayınız!");
}
public void createNotification(Context context, String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, ilac_hatirlatma.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.app_icon).setContentTitle(msg).setTicker(msgAlert).setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
Here i prepare the alarm manager, every day at same hour
alarmManager = (AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(getApplicationContext(), MyBroadcastReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, 0);
// Set the alarm to start at some time.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
int curHr = calendar.get(Calendar.HOUR_OF_DAY);
// Checking whether current hour is over 15
if (curHr >= 15)
{
// Since current hour is over 15, setting the date to the next day
calendar.add(Calendar.DATE, 1);
}
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 30);
// every day
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
And here i have the BroadcastReceiver that generate the notification
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
//Partial_wake_lock only need CPU active
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "tag");
//Acquire the lock
wl.acquire();
int mId = 0;
//Show the notification
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ic_action_edit)
.setContentTitle("YOUR APP NAME")
.setContentText("TAKE THE PILLS!")
.setAutoCancel(true)
.setDefaults(-1);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
//Release the lock
wl.release();
}
}
The permissions of the manifest
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
And Receiver declaration in the manifest
<receiver android:name=".MyBroadcastReceiver" />
For setting your Alarm manager read documentation
If you need to pass data between AlarmManager and BroadcastReceiver use .putExtra() like how this post explain
Hope this helps!
i have an android with a date picker.
i would like to choose a date and save it with an action bar item.
at this moment, it should be set an notification with the selected date.
this is my first time with notifications.
can everybody tell me, how i realize this?
i use min. SDK 15
i try something like this, but with this the notification start directly:
intent = new Intent(this, Overview.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
long[] pattern = {200,200,200,200,200,200,200,200,200};
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Notification n = new Notification.Builder(this)
.setContentTitle("My Titel")
.setContentText("This is the Body")
.setSmallIcon(R.drawable.ic_notification_appicon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.setLights(Color.GREEN, 500, 500)
.setVibrate(pattern)
.setSound(alarmSound)
.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
if you want to set a notification it should notify at n date you need to use a broadcast receiver and because a broadcast receiver up only for a short time its a better practice to use also intent service here you have a example how to do it.
this is the broadcast receiver class.
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1 = new Intent(context, MyNewIntentService.class);
context.startService(intent1);
}
}
and register it in the manifest.
<receiver
android:name=".MyReceiver"
android:enabled="true"
android:exported="false" >
</receiver>
this is the intent service class.
public class MyNewIntentService extends IntentService {
private static final int NOTIFICATION_ID = 3;
public MyNewIntentService() {
super("MyNewIntentService");
}
#Override
protected void onHandleIntent(Intent intent) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("My Titel");
builder.setContentText("This is the Body");
builder.setSmallIcon(R.drawable.ic_notification_appicon);
builder.setAutoCancel(true);
builder.setLights(Color.GREEN, 500, 500);
Intent notifyIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 2, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notificationCompat = builder.build();
NotificationManagerCompat managerCompat = NotificationManagerCompat.from(this);
managerCompat.notify(NOTIFICATION_ID, notificationCompat);
}
}
and register it in the manifest.
<service
android:name=".MyNewIntentService"
android:exported="false" >
</service>
and then in your activity set the alarm manger to start the broadcast receiver at a specific date like this this example use the date picker to help you with that:
DatePicker datePicker= (DatePicker)timeDialogView.findViewById(R.id.yourid);
and:
Calendar now = Calendar.getInstance();
Calendar current = Calendar.getInstance();
now.set(now.get( datePicker.getYear()), now.get(datePicker.getMonth()), now.get(datePicker.getDayOfMonth()), the hour, and the minute);
if(now.compareTo(current)<=0){
Toast.makeText(MainActivity.this,"invalid time",Toast.LENGTH_LONG).show();
}
else{
Intent notifyIntent = new Intent(context, MyReceiver.class);
notifyIntent.putExtra("title",item.getText());
PendingIntent pendingIntent = PendingIntent.getBroadcast
(context, NOTIFICATION_REMINDER, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC,now.getTimeInMillis(), pendingIntent);
}
i hope this will help you!