Having trouble coding recurring notifications for Android? - 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)

Related

After receiving alarm notification , page not directed to another activity?

I am a newbie in android developement.I have set an alarm at an 5 seconds interval.
So once the alarm is triggered, I have set a notification.But when I select notification,I configured the page to move some other activity .But nothing is happen.
public class Snooze extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intent1=new Intent(context,NotificaitonPage.class);
intent1.putExtra("notify","SNOOZE") ;
intent1.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
int requestCode = 0;
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, requestCode, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder noBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Push notification alerts")
.setContentText("This for alaram notification")
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setStyle(new NotificationCompat.BigTextStyle().bigText("This for alaram notification")) ;
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, noBuilder.build()); //0 = ID of notification
}
}
So, Please help me to solve the problem.
Advance Thanks.
When you create PendingIntent you should use PendingIntent.getActivity() instead of PendingIntent.getBroadcast. See more link
Add the following flag to your intent1:
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
As pointed out by #Alexander in another answer, you also need to setup your PendingIntent as:
pendingIntent.getActivity();

generating notification when time matches, even without running application - ANDROID

In my android application, I want to generate a notification when current time matches with the time that I have retrieved from my database. And the notification should be generated even if the application is not running. For this I have done something like this, but this is not working (no notification is being generated).
I am new to android, and I have seen many examples and tutorials for solving this issue, but they did not helped. So please give Answer that what should I do for getting the desired result?
In MainActivity.java I am doing this:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*here I am retrieving time from database*/
String time_from_database = "20:00:00";
if(Calendar.getInstance()==time_from_database) {
AlarmManager alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, NotGen.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
alarmMgr.set(AlarmManager.RTC, Calendar.getInstance(), alarmIntent);
}
}
}
this is code of NotGen.java class:
public class NotGen extends BroadcastReceiver {
public NotificationCompat.Builder mBuilder;
#Override
public void onReceive(Context context, Intent intent) {
PendingIntent pIntent = PendingIntent.getActivity(context,0,intent,0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);
mBuilder.setTicker("Ticker Title");
mBuilder.setSmallIcon(R.drawable.my_img);
mBuilder.setContentTitle("Notification Alert, Click Me!");
mBuilder.setContentText("Hi, This is Android Notification Detail!");
mBuilder.setContentIntent(pIntent).getNotification();
mBuilder.setAutoCancel(true);
mBuilder.getNotification().flags |= Notification.FLAG_AUTO_CANCEL;
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0,mBuilder.build());
}
}
Calendar.getInstance()==time_from_database will never work.
First, getInstance() is going to create a new instance, and == is object identity equality.
Second, time_from_database is a String ("20:00:00"). A Calendar instance will never equal that, if for no other reason than a Calendar is a combination of date and time.
You can achieved it using Service. Service will running in background all the time even your application is not running.
1) Create service and register it into Manifest file.
2) Start it on application start.
3) Into service you can generating your notification when current time will matched with database time.
For service example you can see below links
http://javatechig.com/android/android-service-example
http://www.tutorialspoint.com/android/android_services.htm

Setting notification/alarm in an android application

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.

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...

Make notification disappear after 5 minutes

Is it possible to make a notification automatically disappear after a period of time?
You can use the AlarmManager. I think is more appropriate and more easier to implement than an Android Service.
With AlarmManager you do not need worry about make something running until the time finish. Android do that for you, and send a brodcast when it happen. Your application must have a Receiver to get the correct intent.
Look theses examples:
Android: How to use AlarmManager
Alarm Manager Example
Now there is an option called .setTimeoutAfter(long durationMs)
https://developer.android.com/reference/android/app/Notification.Builder.html#setTimeoutAfter(long)
Yeah, you can just create a service that runs in the background that'll timeout after five minutes and delete your notification. Whether you "should" actually do that is up for debate. A notification should be there to notify the user... and the user should be able to dismiss it on their own.
From d.android.com:
A Service is an application component that can perform long-running
operations in the background and does not provide a user interface.
Yeah, it is very easy.
Where you get notification there add one handler if notification is not read by user then remove notification.
#Override
public void onMessageReceived(RemoteMessage message) {
sendNotification(message.getData().toString);
}
add notification code
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("TEST NOTIFICATION")
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
int id = 0;
notificationManager.notify(id, notificationBuilder.build());
removeNotification(id);
}
cancel notification code.
private void removeNotification(int id) {
Handler handler = new Handler();
long delayInMilliseconds = 20000;
handler.postDelayed(new Runnable() {
public void run() {
notificationManager.cancel(id);
}
}, delayInMilliseconds);
}
You could also use a classic Java Runnable for a simple small Thread.
Handler h = new Handler();
long delayInMilliseconds = 5000;
h.postDelayed(new Runnable() {
public void run() {
mNotificationManager.cancel(id);
}
}, delayInMilliseconds);
Also look here:
Clearing notification after a few seconds

Categories

Resources