Setting notification/alarm in an android application - android

I am building a simple android app for java tutorial in which i want to keep one read later option using which the user can schedule a time for reading and at the specified time my app should give a notification to the user. Even if my app is not opened at that time he should get the notification in notifications bar.I am a newbie in android and have no idea about how to do this.Can someone please help me out?As a i am a newbie a detailed explanation can be more helpful.Thanks in advance :-)

To schedule a delayed notification, you
1) Create a BroadcastReceiver that will receive the event:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//you might want to check what's inside the Intent
if(intent.getStringExtra("myAction") != null &&
intent.getStringExtra("myAction").equals("notify")){
NotificationManager manager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.yourIcon)
//example for large icon
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setContentTitle("my title")
.setContentText("my message")
.setOngoing(false)
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setAutoCancel(true);
Intent i = new Intent(context, YourTargetActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(
context,
0,
i,
PendingIntent.FLAG_ONE_SHOT
);
// example for blinking LED
builder.setLights(0xFFb71c1c, 1000, 2000);
builder.setSound(yourSoundUri);
builder.setContentIntent(pendingIntent);
manager.notify(12345, builder.build());
}
}
}
Don't forget to declare it in the Manifest:
<receiver
android:name="your.package.name.MyReceiver"
android:exported="false" />
2) Schedule the action (assumed you do it from an Activity):
//will fire in 60 seconds
long when = System.currentTimeMillis() + 60000L;
AlarmManager am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, MyReceiver.class);
intent.putExtra("myAction", "mDoNotify");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, when, pendingIntent);
3) You're done
//Disclaimer: haven't compiled the code, typos possible. The rest is your homework ;)

Use AlarmManager to solve your problem. And when alarm is received, you can send a notification too.
See this sample app in android's tutorial for implementing the alarms.

Related

How to cancel a repeating notification on a particular date

Well I have tried enough to look for the answer to the question mentioned above, but my efforts have been futile so far.
I have created an alarm with the help of the alarmmanager class which will fire up the notification at regular intervals of time(probably about 5 days).
Below is the code for the implementation of the alarm happening inside onClick() of a button.
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
PendingIntent broadcast = PendingIntent.getBroadcast(this, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar cal = Calendar.getInstance();
if(fromDateEtxt.getText().toString().length()>0) {
cal.add(Calendar.HOUR_OF_DAY, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5 * 24 * 60 * 60 * 1000, broadcast);
}
The code for the broadcast receiver.
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent notificationIntent = new Intent(context, NotificationActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(NotificationActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
Notification notification = builder.setContentTitle("Demo App Notification")
.setContentText("New Notification From Demo App..")
.setTicker("New Message Alert!")
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notification);
}}
The onClick() method apart from starting of the alarm changes the activity also. Now the problem I am facing is I dont know really how to stop the repeating alarm. I want to stop the alarm on a particular date. Secondly, I was confused whether to use the alarm.cancel for cancelling the alarm or to use another alarm for cancellation of the previous alarm as shown here. Apart from this, I wanted to know if the alarm could be cancelled from another activity or does the point seems unnecessary and the limit to the date could be set beforehand?

How can I cancel unshown notifications in android

Hi I am new to notifications,
I wrote this code for notifications.
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus,
myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
In that I set one list of notifications. In that some displayed and some not displayed. But I want to cancel all un shown notifications.
I used mNotificationManager.cancleAll() but that is cancel only shown notifications.
thanks in advance.
I think the problem here is that The Notification is launched immediately after creating it and your not using the AlarmManager to schedule this Notification.
Solution Should be to schedule Alarms via an AlarmManager which will trigger the Notification Code above.
This requires 3 parts:
Register a BroadCastReceiver & Build a Notification when its triggered:
public class UtilityReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// .. Here is where you really want to build the notification and notify
// This will be triggered by the AlarmManager from the Code below
PendingIntent pendingIntent = PendingIntent.getActivity(context, leadidforstatus, myIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.noti)
.setContentTitle("LMS notification")
.setContentIntent(pendingIntent)
.setContentText(intent.getStringExtra("messagenotify"))
.setAutoCancel(true);
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
}
Schedule an Alarm with the AlarmManager to send a BroadCast which the Receiver above is listening for:
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, timeForAlarmInMillis, notificationPendingIntent);
Then when you encounter the situation when you no longer want notifications to show for your app, you tell the AlarmManager to remove them from its queue of Alarms by Rebuilding the pending Intent and using AlarmManager to Cancel it.
// Create an Intent to Launch
Intent notificationIntent = new Intent(context, UtilityReceiver.class);
// Use a Pending Intent to Launch the Alarm
PendingIntent notificationPendingIntent = PendingIntent.getBroadcast(context,
PendingIntent.FLAG_ONE_SHOT, notificationIntent, Intent.FILL_IN_DATA);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// *********Important this will cancel all the Matching PendingIntents
alarmManager.cancel(notificationPendingIntent);
Good Luck, and be sure to register your Receiver in your Activity or Manifest.
NotificationManager maintains list of all notification mNotificationList and performs cancel or cancelAll operations on this list
I tried searching in Google source code of NotificationManager.java and NotificationManagerService.java in notify(),enqueueNotificationWithTag() and cancelAllNotification() But there is no implementation to cancel previously unshown notification
As per your comment, if your user is deleted and his notification arrives then user is already deleted so notification has no meaning
i = (int) System.currentTimeMillis();
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(i, mBuilder.build());
// i should be Id for this notification, i think you want to pass
// time in mili second here
I think you are searching similar to this,
How to dismiss notification after action has been clicked
Just check the answer on that post. Use the id to cancel that particular Notification
I think the id part in your code is this,
i = (int) System.currentTimeMillis();

Alarm Manager showing abnormality

I have set an Alarm Manager which will show Notification 10 seconds after app will be destroyed.
But it's not working.
Here's my onDestroy() code:
#Override
public void onDestroy() {
super.onDestroy();
Intent myIntent = new Intent(this, alarmManager.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent,0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
//alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, 10*1000, 10*1000, pendingIntent);
alarmManager.cancel(pendingIntent);
}
and here is alarmManager.class:
public class alarmManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, Notification.class);
context.startService(service1);
}
}
and here is Notification.class:
public class Notification extends Service {
#Override
public void onCreate() {
super.onCreate();
Intent mainIntent = new Intent(this, Main.class);
NotificationManager notificationManager
= (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
android.app.Notification noti = new NotificationCompat.Builder(this)
.setAutoCancel(true)
.setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle("Title")
.setContentText("It's been so Long!!!")
.setSubText("Please return back to App")
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[] {1000,1000,1000,1000})
.setSmallIcon(R.drawable.ic_launcher)
.setTicker("Important Notification")
.setWhen(System.currentTimeMillis())
.build();
notificationManager.notify(0, noti);
}
*I've been working on this since many days, but I am unable to get through it.
Any Help would be highly* appreciated.
Thanks in advance.
There are some relatively minor changes to make, but overall you've got the necessary code.
You don't need a Service for this. Move the code to create the Notification to the BroadcastReceiver, and replace this with context everywhere.
Make sure your BroadcastReceiver is listed in the manifest.
Don't use setRepeating() for the alarm; use set(). You only need it to fire once.
Remove the following line: alarmManager.cancel(pendingIntent);
Those are the changes necessary to get it working. However, you might also consider removing the sound and vibration from the Notification, and treat it more like a status message. It would also be preferable to rename your BroadcastReceiver class. Perhaps something like AlarmReceiver, to be in keeping with Java class naming conventions, and to avoid confusion with the AlarmManager class.

I have notification running. I just need to make it appear at a specific time

I searched all similar questions/answers but I can't get it to work with my code! I can get the notification to appear instantly. However, I need it to appear 24 hrs after the user runs the app. I am stuck. I tried using Alarm Manager with no success. Here is my working code. Please guide me. Thanks.
public class NotifyNow {
static void noty(Context context, String message) {
int icon = R.drawable.ic_launcher;
long when = System.currentTimeMillis();
String appname = context.getResources().getString(R.string.app_name);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification;
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context);
notification = builder.setContentIntent(contentIntent)
.setSmallIcon(icon).setTicker(appname).setWhen(0)
.setAutoCancel(true).setContentTitle(appname)
.setContentText(message).build();
//notification.defaults |= Notification.DEFAULT_SOUND;
notification.sound =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notificationManager.notify(0 , notification);
}
I call it from my MainActivity class as follows:
NotifyNow.noty(this,"Notification worked");
How do I implement the alarm. I would appreciate detailed answer as I am fairly new to java.
You can find Current DateTime using Date APIs, when your app runs by overcreate riding onStart() of Activity.
e.g.
currentTime = SystemClock.currentThreadTimeMillis();
Now, you can add an alarm using AlarmManager API.
AlarmManager Refernce
Note: The Alarm Manager is intended for cases where you want to have your application code run at a specific time,
even if your application is not currently running. For normal timing operations (ticks, timeouts, etc) it is easier
and much more efficient to use Handler.
Sample Code for Creating an alarm is:
private AlarmManager alarmMgr;
private PendingIntent alarmIntent;
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
alarmMgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
currentTime +
24 * 60 * 60 * 1000, alarmIntent);
Please Note: This code is not tested, but just a concept of requisite. Let me know if you face any issue.
I have tried this...
put uppercase notification service
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notifyDetails=new Notification(
R.drawable.icon,contentTitle,System.currentTimeMillis());
notificationManager .notify(MY_SIMPLE_NOTFICATION_ID, notifyDetails);
You can achieve this by using this library also...

Having trouble coding recurring notifications for Android?

I would like to send my users a notification message every 12 hours, but am having trouble figuring out where to start. Can somebody please provide a step by step guide to adding a simple notification to my users? Thanks in advance
Steps are:
Setup an Alarm via AlarmManager
On BroadcastReceiver of alarm fire populate a Notification you can then setup the next alarm in 12h
Another way is to create from the beginning recurring every 12h.
see this example AlarmManager and Notification in Android
you can use this code:
private static final int TIME = 1000*60*60*12;
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
showNotification();
}
}, 0, TIME);//start immediatly, run every 12hours
public void showNotification() {
final NotificationManager mNotification = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
final Intent launchNotifiactionIntent = new Intent(this, ActivityLauchedOnClickNotif.class);
final PendingIntent pendingIntent = PendingIntent.getActivity(this,
REQUEST_CODE, launchNotifiactionIntent,
PendingIntent.FLAG_ONE_SHOT);
Notification.Builder builder = new Notification.Builder(this)
.setWhen(System.currentTimeMillis())
.setContentTitle(titleString)
.setContentText(messageString)
.setContentIntent(pendingIntent);
mNotification.notify(NOTIFICATION_ID, builder.build());
}
this code works since API 11 ! (notification.builder)

Categories

Resources