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!
Related
I added a notification feature to my app, when the user clicks on the notification it sends him to a certain activity in my app, but I also want it to change an integer variable number, I tried defining the variable static and do:
ActivityName.Variable = ActivityName.Variable + 1 or ActivityName.Variable++;
And it actually worked! but only when I change the date on my phone manually, so when the user sees the notification after waiting 1 day (the notification is daily) and clicks on it...he get to the activity but with no increase in the variable.
here's the notification codes:
public void setNotificationOn() { //This method sets the notification...so after 24h it will be triggered
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 24);
Intent intent = new Intent(getApplicationContext(), NotificationReceiverActivity.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_DAY, pendingIntent);
}
package com.example.wordspuzzlejsontest;
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
LevelActivity.stars++; //This is the variable which I'm trying to increase
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, LevelsListActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity
(context, 100, repeating_intent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setSmallIcon(android.R.drawable.star_big_off)
.setContentTitle("Collect your daily star")
.setContentText("Click to collect your daily star")
.setAutoCancel(true)
.setColor(Color.BLUE);
notificationManager.notify(100, builder.build());
}
}
Not sending notification at selected time, when I ran my code, directly showed notification
and showed error as well
Here is the error message: E/NotificationManager: notifyAsUser: tag=null, id=12345, user=UserHandle{0}
I thought the error message was due to Build.VERSION.SDK_INT, but after adding that, the error message is still there.
Place all of these under onCreate:
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 13);
calendar.set(Calendar.MINUTE,9)
;
Intent intent = new Intent ();
intent.setAction("com.example.Broadcast");
PendingIntent contentIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, contentIntent);
and here is the extend.
public class wakeReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
setNotification(context);
}
protected void setNotification(Context context){
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
String ChannelId = "12345";
int uniID = 12345;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,ChannelId )
.setSmallIcon(R.mipmap.ic_launcher_round)
.setContentTitle("Hi")
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.setContentText("Please Rate.");
builder.setContentIntent(contentIntent);
//
// Send notification to your device
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
builder.setChannelId("com.myApp");
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
"com.myApp",
"My App",
NotificationManager.IMPORTANCE_DEFAULT
);
if (manager != null) {
manager.createNotificationChannel(channel);
}
}
manager.notify(uniID, builder.build());
}
}
Can someone please help me with this?
You are very confused.
In your code you call NotificationManager.notify(). This will show the Notification immediately.
You do:
Intent intent = new Intent(this, MainActivity.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this,0, intent,0);
This won't work. You have created a PendingIntent which will be sent via broadcast using an Intent that is for an Activity! What do you want to happen? Do you want an Activity to be launched or do you want a BroadcastReceiver to be triggered?
I think what you want to do is as follows:
Create an Intent for a BroadcastReceiver, wrap that in a PendingIntent using getBroadcast() and pass that to the AlarmManager so that the broadcast Intent will be set at some future time.
Create a class that extends BroadcastReceiver. In onReceive() create the Notification and call NotificationManager.notify() to post the Notification. In the Notification you can set a PendingIntent that opens your Activity so that if the user clicks on the Notification your Activity will be launched. To do this, call PendingIntent.getActivity() and pass an Intent that contains MainActivity.class.
So my program is supposed to set off a notification a few hours after the application has been stopped (minutes are being used just now for testing). It does this, however the problem with it is that if the code is executed a second time before a notification has been pushed, then no notification is pushed at all.
Override
public void onStop() {
super.onStop();
Calendar calendar = Calendar.getInstance();
int alarmTime = (calendar.get(Calendar.MINUTE)) + 3;
calendar.set(Calendar.MINUTE,alarmTime);
Intent intent3 = new Intent(getApplicationContext(),timeReceiver.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(),100,intent3,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent3);
}
#Override
protected void onRestart() {
super.onRestart();
//this.onCreate(null);
}
This is what my broadcast receiver class looks like...
public class timeReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, RepeatingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(android.R.drawable.arrow_up_float);
builder.setContentTitle("Timer Notification");
builder.setContentText("blaaah blaaah blah");
builder.setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
My expectation is that the alarm would reset and trigger 3 minutes after the last execution of the onStop() method, but this does not happen. I don't really understand why it doesn't, if anyone could give me insight/ a possible solution I would be grateful. Also the SDK version is 24.
You can schedule your notification with NotificationCompat.Builder#setWhen(long), no need for alarm manager.
int notification1Id = 56748;
Calendar calendar = Calendar.getInstance();
int alarmTime = (calendar.get(Calendar.MINUTE)) + 2;
calendar.set(Calendar.MINUTE,alarmTime);
long timeMs = calendar.getTimeInMillis();
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
final PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
// Build notifications
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, channelID);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(android.R.drawable.arrow_up_float);
builder.setContentTitle("It's been a while...");
builder.setContentText("Remember to keep track of your calories using the calorie counter");
builder.setAutoCancel(true);
builder.setWhen(timeMs);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notification1Id, builder.build());
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'm trying to send a notification to a user at a specific time using an Alarm Manager. Basically, nothing happens at all and to me the code looks fine. My code for the Alarm Manager is below:
/** Notify the user when they have a task */
public void notifyAtTime() {
Intent myIntent = new Intent(PlanActivity.this , Notification.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(PlanActivity.this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 17);
calendar.set(Calendar.SECOND, 00);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24*60*60*1000 , pendingIntent);
}
The code for the notification, which is in the "Notification" class is below:
public class Notification extends Service {
#Override
public void onCreate() {
Toast.makeText(this, "Notification", Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,PlanActivity.class);
PendingIntent pending = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Football")
.setContentText("Don't forget that you have Football planned!")
.setContentIntent(pending);
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
manager.notify(0, mBuilder.build());
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
The Toast which is set in the Notification class also doesn't come up. I don't know if it's something really silly that I'm missing but any help would be greatly appreciated! :)
This is your receiver class :
public class OnetimeAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
//Toast.makeText(context, "Repeating Alarm worked.", Toast.LENGTH_LONG).show();
// try here
// prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
// build notification
// the addAction re-use the same intent to keep the example short
Notification n = new Notification.Builder(this)
.setContentTitle("New mail from " + "test#gmail.com")
.setContentText("Subject")
.setSmallIcon(R.drawable.icon)
.setContentIntent(pIntent)
.setAutoCancel(true)
.addAction(R.drawable.icon, "Call", pIntent)
.addAction(R.drawable.icon, "More", pIntent)
.addAction(R.drawable.icon, "And more", pIntent).build();
NotificationManager notificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, n);
}
}
In Second Activity to set Alerm :
private void setAlarm(){
Intent intent = new Intent(this, OnetimeAlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, REQUEST_CODE, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + alarm_time , pendingIntent);
System.out.println("Time Total ----- "+(System.currentTimeMillis()+total_mili));
}
I would like to recommend this tutorial How to send notification
Try to put your notification code in the onStartCommand function instead of onCreate.
Writing the alarmmanager code in the onCreate method of the LAUNCHER activity of the app solved my problem