Notification based on time item in listview - android

I have an arraylist of objects, a member of which is a date/time.
The arraylist and object is used to populate the UI listview.
I would like to send a push notification when the time from the object/listview is approaching system/mobile time (whether its 5, 10 mins or modifiable, doesn't matter).
So i'm familiarizing myself with the Notification Builder, but i'm unsure where to put the logic and how the app will monitor the time and notify when its close.
Any ideas, suggestions on the right path much appreciated

You can trigger an alarm at a scheduled time and then use an IntentService to capture it once alarm goes off.
In the main activity (lets assume the name is MainActivity, you can create an alarm like this.
AlarmManager mgr = (AlarmManager) MainActivity.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity, NotifService.class);
PendingIntent pi = PendingIntent.getService(MainActivity, 0, intent, 0);
mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + PERIOD, pi);
where the PERIOD defines after how much milliseconds you want the alarm to go off.
To configure the AlarmManager differently, you can read more about it.
NotifService is what captures the alarm when it goes off. Create a class called NotifService it extends IntentService
public class NotifService extends IntentService {
public NotifService() {
super("My service");
}
#Override
protected void onHandleIntent(Intent intent) {
//write your code for sending Notification
Intent intent = new Intent();
intent.setAction("com.xxx.yyy.youractivitytobecalled");
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder (getApplicationContext());
builder.setContentTitle("Your Application Title");
builder.setContentText("Notification Content");
builder.setContentIntent(pendingIntent);
builder.setTicker("Your content");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setOngoing(false);
builder.setPriority(0);
Notification notification = builder.build();
NotificationManager notificationManger = (NotificationManager) getSystemService (Context.NOTIFICATION_SERVICE);
notificationManger.notify(1, notification);
}
}
Register NotifService in your AndroidManifest.xml
<application
fill content here />
<service android:name=".NotifService" >
</service>
</application>

Just for future reference, I created a class that extends BroardcastReceiver and used that to handle the alarms from AlarmManager - its all there in the docs but its kinda confusing how everything sits together at first.

Related

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.

AlarmManager Not called next day if the app sleeps for abt 1 day

I am developing an android app which shows a notification every 12 hour if the time is saved in the database. So everytime a data is entered or edited in the database ,I cancel the current alarmmanager and start a fresh new one so that I dont miss one. Also on reboot I have called the alarmmanager. On the broadcast receiver, the database is checked for entry and if found a notification is set and the app is opened automatically.
So when I test the app by changing the date manually,the app works as expected.Also on reboot the app works.But if I keep the app idle for nearly 14 hours,the notification is not set ,but if I open the app and suspend it the notification is set after that.
This is how I call the alarmmanager.
Intent alarmintent = new Intent(context, package.Alarm_Manager.class);
alarmintent.putExtra("note","Notify");
sender = PendingIntent.getBroadcast(context , 0 , alarmintent , PendingIntent.FLAG_CANCEL_CURRENT | Intent.FILL_IN_DATA);
alarm_manger = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarm_manger.cancel(sender);
Calendar cal = Calendar.getInstance();
long now = cal.getTimeInMillis();
alarmintent = new Intent(context, package.Alarm_Manager.class);
alarmintent.putExtra("note","Notification");
sender = PendingIntent.getBroadcast(context , 0 , alarmintent , PendingIntent.FLAG_CANCEL_CURRENT | Intent.FILL_IN_DATA);
alarm_manger = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm_manger.setRepeating(AlarmManager.RTC_WAKEUP, now, AlarmManager.INTERVAL_HALF_DAY, sender);
This is the broadcast receiver
#Override
public void onReceive(Context context, Intent intent)
{
NotificationManager manger = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Calendar cal = Calendar.getInstance();
date = (int)(cal.getTimeInMillis()/1000);
Notification notification = new Notification(R.drawable.vlcsnap_396460 , "Notify" , System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
notification.setLatestEventInfo(context, "App", "Notify" , contentIntent);
notification.flags = Notification.FLAG_INSISTENT;
manger.notify( 0 , notification);
}
You don't need to call alarm_manager.cancel(sender); if you set the PendingIntent.FLAG_CANCEL_CURRENT.
Your call to
alarm_manger.setRepeating(AlarmManager.RTC_WAKEUP, now, AlarmManager.INTERVAL_HALF_DAY, sender);
will trigger the alarm right away, since the now is already passed when you set the alarm.
I suggest you use
now + DateUtils.HOUR_IN_MILLIS / 2
for the triggerAtMillis parameter
Did you tried to schedule it for smaller interval? Does it get triggered ?
After having seen your Alarm_Manager code, I think it is illegal to do this in your BroadcastReceiver object directly. Quote:
If this BroadcastReceiver was launched through a tag, then the object is no longer alive after returning from this function.
I believe there is no other way than to create a Service which is informed by your BroadcastReceiver, and make sure that the Service calls setLatestEventInfo() with itself (this) as the Context.
The reason why your asynchronous Broadcast fails while it works when your app is running is probably that the Context provided to the BroadcastReceiver lives only for the duration of the call to the BroadcastReceiver when your app does not run. So the Notification service, which only runs after your BroadcastReceiver has died along with the temporary context, is missing a valid context.
When your app runs, the Broadcast probably comes with your Activity or Application object as Context, and this is still vaild when the Notification manager runs.
Hope this helps.
Update: An `IntentService`` will do. You don't want a full time Service for that.
Update 2: Some snippets.
<service android:name=".MyIntentService" android:label="#string/my_intent_service_name" />
public final class MyIntentService extends IntentService {
public MyIntentService() {
super("service name");
// set any properties you need
}
#Override
public void onCreate() {
super.onCreate();
// do init, e.g. get reference to notification service
}
#Override
protected void onHandleIntent(Intent intent) {
// handle the intent
// ...especially:
notification.setLatestEventInfo(this, "App", "Notify" , contentIntent);
// ...
}
}
public final class MyAlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, MyIntentService.class));
}
}

How to develop Android Alarm application

I tried to develop a sample Alarm Application. I searched Google and SC, most of their examples confused. How can I create an alarm application with the following requirements,
In My Home screen i have a button, like "START ALARM", when i click the button a time picker must enable.
I select the time as I wish, once I pick the time, the alarm icon will enabled on widget. (For example if we set the alarm in default mobile Alarm application, the icon will be enabled, that indicates the alarm is set).
When the set time is reached (the time which is set form the TimePicker app), the alarm will beep.
These are my requirements, I finished the first two points, but I'm still struggling on setting the alarm.
Take a look at AlarmManager. And, If you want to use alarm simultaneously you must use Service class for that. And, see below sample code -
public class OnBootReceiver extends BroadcastReceiver {
private static final int PERIOD=300000; // 5 minutes
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager mgr =
(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0, i, 0);
mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime()+60000, PERIOD, pi);
}
This will repeat the alarm with every 6 Mins. See Scheduling Repeating Alarms document.
when you enable the alarm you have to call inbuilt alarm manager and use the alarmmanager.set to set the alarm time in the manager.
Once the alarm time (in milliseconds) is given to the alarm manager it will send message and you can retrive the message through reciever class
//creating and assigning value to alarm manager class
Intent AlarmIntent = new Intent(MainActivity.this, AlarmReciever.class);
AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent Sender = PendingIntent.getBroadcast(MainActivity.this, 0, AlarmIntent, 0);
AlmMgr.set(AlarmManager.RTC_WAKEUP, Alarm.getTimeInMillis(), Sender);
For recieving the alarm you have to make a new class which extends reciever where in onrecieve you can set the intent to the activity u want to call on alarm time , you can also provide notification.
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{ //Build pending intent from calling information to display Notification
PendingIntent Sender = PendingIntent.getBroadcast(context, 0, intent, 0);
NotificationManager manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
Notification noti = new Notification(android.R.drawable.stat_notify_more, "Wake up alarm", System.currentTimeMillis());
noti.setLatestEventInfo(context, "My Alarm", "WAKE UP...!!!", Sender);
noti.flags = Notification.FLAG_AUTO_CANCEL;
manager.notify(R.string.app_name, noti);
//intent to call the activity which shows on ringing
Intent myIntent = new Intent(context, Alarmring.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);
//display that alarm is ringing
Toast.makeText(context, "Alarm Ringing...!!!", Toast.LENGTH_LONG).show();
}}
If you still get any problem ask again..:)
If you want to make things interesting, you can try to create one without a possibility of dismissing/snoozing. I made this a while ago, you can read about it in this tutorial:
Alarm Application in Android (Tutorial using AlarmManager)
And test the app functionality by downloading this app:
Oversleeper on Google Play
To finish your last point you need to do Date Comparision and use AlaramManager Alaram Doc and again you need to use Service
to compare next date and time. Hope it will helpful for you.
You need to use RingtoneManageror the NotificationManager(to show any text or image to the user for notification at the top of screen), Or you can use MediaPlayerto set to play sound when alarm time is reached. You have to set <receiver> tag in manifest file, that must include a class extending BroadCastReceiver. In the receiver class you can write your code to wake your device up.

Create timed notification (e.g. for events) in Android

For some Android applications, I would like to integrate the following feature:
The user can define a time when he wants to be reminded of something. When the time has come then, the application should create a notification in the notification bar even when the user doesn't use the app at this moment.
For this purpose, the classes AlarmManager, NotificationManager und Notification.Builder are the ones to look at, right?
So how do I create a timed notification in advance? My code (so far) is this:
Add this under to the AndroidManifest to register the broadcast receiver:
<receiver android:name="AlarmNotificationReceiver"></receiver>
Create a new class file which handles the alarm that it receives:
public class AlarmNotificationReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String additionalData = extras.getString("displayText");
// show the notification now
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification mNotification = new Notification(R.drawable.ic_launcher, context.getString(R.string.app_name), System.currentTimeMillis());
PendingIntent pi = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); // open MainActivity if the user selects this notification
mNotification.setLatestEventInfo(context, context.getString(R.string.app_name), additionalData, pi);
mNotification.flags |= Notification.FLAG_AUTO_CANCEL | Notification.DEFAULT_SOUND;
mNotificationManager.notify(1, mNotification);
}
}
}
Use this code (for example in MainActivity) to set the alarm to 3 seconds from now:
Intent i = new Intent(this, AlarmNotificationReceiver.class);
i.putExtra("displayText", "sample text");
PendingIntent pi = PendingIntent.getBroadcast(this.getApplicationContext(), 234324246, i, 0);
AlarmManager mAlarm = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+3*1000, pi);
What do I need to change to make this work? Thank you!
The two problems are:
The notification's text does not change when I change it in code. It only changes when I change the requestCode in PendingIntent.getBroadcast(...). What is this request code all about? Can it be a random value or 0?
After rebooting my phone, the "planned" notification, or the alarm, is gone. But now I've seen that this is normal behaviour, right? How can I circumvent this?
Not sure about part 1, but for part 2 the general approach is to intercept the BOOT_COMPLETED intent and use that to re-register all alarms. This does unfortunately mean that for each alarm you have registered with the alarm manager you have to store it in your app's db as well.
So, you'll need a broadcast receiver to intercept the BOOT_COMPLETED intent:
public class BootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get your stored alarms from your database
// reregister them with the alarm manager
}
}
To get the BOOT_COMPLETED intent, you must put the following permission in your manifest:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
And the BootReceiver also needs to be registered in your manifest with the following intent filter:
<receiver android:enabled="true" android:name=".receiver.BootReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
It's important to note that if your app is installed to the sdcard, it can never receive the BOOT_COMPLETED intent. Also, it's worth noting that this implementation is a bit naive in that it executes code immediately on booting which can slow the user's phone down at startup. So, I recommend delaying your execution for a few minutes after intercepting the boot intent.
I personally would do it without a Broadcast Receiver. I'd get the AlarmManager to fire the intent to start a seperate Activity, rather than receiver. Then this new Activity could make the notification for you. I'm not sure if this is a better way, but it seems less complicated to me.
Edit: A Service would probably be better still than an Activity
In your MainActivity:
Intent i = new Intent(getBaseContext(), NotificationService.class);
PendingIntent pi = PendingIntent.getService(getBaseContext(), 0, i, 0);
AlarmManager mAlarm = (AlarmManager) Context.getSystemService(Context.ALARM_SERVICE);
mAlarm.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+10*60*1000, pi);
Your Service:
public class NotificationService extends Service {
public int onStartCommand(Intent intent, int flags, int startId) {
//Create the notification here
return START_NOT_STICKY;
}
Your Manifest:
<service android:name="com.android.yourpath.NotificationService"></service>

Categories

Resources