Android Reminder Application - android

I need to create reminder application based on the date and time from the database (Eg:31-08-2011 10:30,05-09-2011 14:40,etc.. )even if the app is not running.. Database will contain many dates with times. If the time reaches i need to display the notificaiton.How can I do that. Please provide any samples or suggestions

You should use AlarmManager for this.
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(), PERIOD, pi);
where the PERIOD is your time to something that should be executed in OnAlarmReceiver.
And then, just implement method in
#Override
public void onReceive(Context context, Intent intent) {
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification();
notification.tickerText = "10 Minutes past";
nm.notify(0, notification);
}
And also see here,
http://developer.android.com/reference/android/app/AlarmManager.html
Edit: A minor code issue fixed!

Put this code wherever you need..
new CountDownTimer(diff, 1) //Constructor for CountDownTimer class (milliseconds,difference);
{
public void onTick(long millisUntilFinished)
{
// DO NOTHING
}
public void onFinish() {
sendSMS(phoneNo,message);
}
}.start();

Related

Scheduled Android Notification push on startup

I am developing the schedule notification for Android. It is successfully get notification at scheduled time but also get notification at the time when the application startup which I do not want. Here are my codes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
prefs= PreferenceManager.getDefaultSharedPreferences(this);
show = (TextView)findViewById(R.id.textView);
View btn_failure = findViewById(R.id.btn_failure_id);
btn_failure.setOnClickListener(this);
View btn_unhappy = findViewById(R.id.btn_unhappy_id);
btn_unhappy.setOnClickListener(this);
View btn_chicken_soup = findViewById(R.id.btn_soup_id);
btn_chicken_soup.setOnClickListener(this);
View btn_no_motivation = findViewById(R.id.btn_no_id);
btn_no_motivation.setOnClickListener(this);
// createScheduledNotification(9,0);
}
#Override
protected void onResume() {
super.onResume();
time = prefs.getString("noti", "9:00");
String[] pieces=time.split(":");
hour = Integer.parseInt(pieces[0]);
minute = Integer.parseInt(pieces[1]);
boolean onOff = prefs.getBoolean("noti_10",true);
createScheduleNotification(hour,minute,onOff);
}
public void createScheduleNotification(int hour, int minute, boolean onOff){
if(onOff){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntent(this));
}else{
AlarmManager mgr=(AlarmManager)this.getSystemService(this.ALARM_SERVICE);
mgr.cancel(getPendingIntent(this));
}
}
private PendingIntent getPendingIntent(Context ctxt) {
Intent intent1 = new Intent(ctxt, TimeAlarm.class);
intent1.putStringArrayListExtra("quotes",quote_chicken_soup);
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctxt, 0,intent1, PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
public class TimeAlarm extends BroadcastReceiver {
private String daily_quote = "testing";
#Override
public void onReceive(Context context, Intent paramIntent) {
NotificationManager manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent(context,DisplayActivity.class);
intent.putStringArrayListExtra("quote",paramIntent.getStringArrayListExtra("quotes"));
daily_quote = paramIntent.getStringArrayListExtra("quotes").get(0);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, 0);
Notification.Builder builder = new Notification.Builder(context);
builder.setAutoCancel(true);
builder.setTicker("Daily Quote");
builder.setContentTitle("Daily Quote");
builder.setContentText(daily_quote);
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentIntent(pendingIntent);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
builder.setSubText("Be Happy! Have a nice day!"); //API level 16
}
Notification myNotication = builder.getNotification();
manager.notify(11, myNotication);
}
}
Where is the problem that cause the notification being push when app startup?
There seems nothing wrong in your code.
Issue with notification being pushed up at startup is surely because of AlarmManager code.
From your code snippet, I hard coded the setting of time as below, and it runs as expected . First time it triggers in one minute after the system clock and then every 2 minutes there after.
// first time set to-- trigger after one minute from now
long firstTimeTriggerAt = SystemClock.elapsedRealtime() + 1000 * 60 * 1;
AlarmManager am = (AlarmManager) MainActivity.this.getSystemService(MainActivity.this.ALARM_SERVICE);
//Repeat the alaram every two minutes
long interval = 1000 * 60 * 2;
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,firstTimeTriggerAt, interval, getPendingIntent(this));
So you need to check the constant values for time, which you are setting in Shared preference.
Just FYI , the code runs well with RTC_WAKEUP constant also.
Hope this helps.
in onResume() change
boolean onOff = prefs.getBoolean("noti_10",true);
to
boolean onOff = prefs.getBoolean("noti_10",false);

Android daily notifications do not work properly

I want to display notification every morning at 9 AM from my app.
So I am using Notification Manager, Alarm Manager, BroadcastReciever and Service to make that possible.
But I have a problem, because the notification shows randomly. When I first start the app and set the time, it works OK, but later the app fires and shows notification at random time.
How I can solve that?
Here is my code:
MainActivity
#Override
protected void onStart() {
super.onStart();
setAlarm();
}
public void setAlarm(){
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 15);
calendar.set(Calendar.MINUTE, 43);
calendar.set(Calendar.SECOND, 0);
if(calendar.getTime().after(now.getTime())) {
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmIntent = new Intent(MainActivity.this, HoroscopeNotification.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent); }
}
HoroscopNotification (BroadcastReciever)
public class HoroscopeNotification extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent arg1) {
showNotification(context);
}
private void showNotification(Context context) {
Intent service1 = new Intent(context, AlarmService.class);
context.startService(service1);
}
}
AlarmService
public class AlarmService extends Service {
private static final int NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;
#Override
public IBinder onBind(Intent arg0)
{
return null;
}
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Context context = this.getApplicationContext();
notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
Intent mIntent = new Intent(this, MainActivity.class);
pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("Horoskop");
builder.setContentText("Pročitajte današnji horoskop");
builder.setSmallIcon(R.drawable.ic_bik);
builder.setAutoCancel(true);
builder.setContentIntent(pendingIntent);
notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}
You'll notice in the Android SDK Reference material for the AlarmManager.setRepeating() states:
Note: as of API 19, all repeating alarms are inexact. If your application needs precise delivery times then it must use one-time exact alarms, rescheduling each time as described above. Legacy applications whose targetSdkVersion is earlier than API 19 will continue to have all of their alarms, including repeating alarms, treated as exact.
You need to use AlarmManager.set() on pre-APIv19 and AlarmManager.setExact() on APIv19+. When your PendingIntent is fired and you receive your Broadcast in your BroadcastReceiver.onReceive() you can set another exact alarm for the next day.
Alarm Manager Example
I think you should follow above link. From my point of view, your design pattern (setting alarm in Activity class is not a good approach). Instead (like showed in the answer above) you should set your alarm from a service. Also the code for notification goes in BroadcastReceiver class, method OnReceive (In the example it is commented "Put here YOUR code").
Good luck

AlarmManager alarm fires immediately

I'm testing AlarmManager to use in my app, and it is firing my Broadcast Receiver immediately when I want it to fire after 1 minute. The code is below:
public class SetMealTimersActivity extends Activity {
PendingIntent pi;
BroadcastReceiver br;
AlarmManager am;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_meal_timers);
br = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent i) {
Toast.makeText(c, "Ready to Go!", Toast.LENGTH_LONG).show();
}
};
registerReceiver(br, new IntentFilter("com.ian.mealtimer"));
pi = PendingIntent.getBroadcast(this, 0, new Intent(
"com.ian.mealtimer"), 0);
am = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
am.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() +
60 * 1000, pi );
}
try :
am.set(AlarmManager.RTC_WAKEUP,
Calendar.getInstance().getTimeInMillis()+60*1000, pendingIntent);
it is working for me.
If using an exact alarm, make sure it's time is in the future. Otherwise it will fire immediately.
Try changing SystemClock.elapsedRealtime() to System.currentTimeMillis() and AlarmManager.ELAPSED_REALTIME_WAKEUP to AlarmManager.RTC_WAKEUP.
Try to use AlarmManager.setExact(int, long, PendingIntent) if you use Android API > 18 or compile with API < 19, because the time management for this methods changed with API 19. Maybe that helps. Read the documentation for more information.
make id for pendingIntent as this
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
All example
public void setAlarm_sat(int dayOfWeek1) {
cal1.set(Calendar.DAY_OF_WEEK, dayOfWeek);
Intent intent = new Intent(this, RemmemberActivity.class);
pendingIntent = PendingIntent.getActivity(this, 999123266,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
Long alarmTime = cal1.getTimeInMillis();
AlarmManager am = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,
alarmTime,7*24 * 60 * 60 * 1000,
pendingIntent);
// am.set(AlarmManager.RTC, cal1.getTimeInMillis(), pendingIntent);
}

Android Notification with AlarmManager, Broadcast and Service

this is my code for menage a single notification:
myActivity.java
public class myActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylayout);
cal = Calendar.getInstance();
// it is set to 10.30
cal.set(Calendar.HOUR, 10);
cal.set(Calendar.MINUTE, 30);
cal.set(Calendar.SECOND, 0);
long start = cal.getTimeInMillis();
if(cal.before(Calendar.getInstance())) {
start += AlarmManager.INTERVAL_FIFTEEN_MINUTES;
}
Intent mainIntent = new Intent(this, myReceiver.class);
pIntent = PendingIntent.getBroadcast(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager myAlarm = (AlarmManager)getSystemService(ALARM_SERVICE);
myAlarm.setRepeating(AlarmManager.RTC_WAKEUP, start, AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
myReceiver.java
public class myReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context c, Intent i) {
Intent myService1 = new Intent(c, myAlarmService.class);
c.startService(myService1);
}
}
myAlarmService.java
public class myAlarmService extends Service {
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#SuppressWarnings("deprecation")
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
displayNotification();
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void displayNotification() {
Intent mainIntent = new Intent(this, myActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationManager nm = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pIntent)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_noti)
.setTicker(getString(R.string.notifmsg))
.setContentTitle(getString(R.string.app_name))
.setContentText(getString(R.string.notifmsg));
nm.notify(0, builder.build());
}
}
AndroidManifest.xml
<uses-permission android:name="android.permission.WAKE_LOCK" />
...
...
...
<service android:name=".myAlarmService" android:enabled="true" />
<receiver android:name=".myReceiver"/>
IF the time has NOT past yet everything works perfectly. The notification appears when it must appear.
BUT if the time HAS past (let's assume it is 10.31 AM) the notification fires every time... when I close and re-open the app, when I click on the notification... it has a really strange behavior.
I can't figure out what's wrong in it. Can you help me please (and explain why, if you find a solution), thanks in advance :)
Place display notification inside an if statement , such that compare the current time with the notification set time and if the current time is before the set time then display notification, else do nothing.
int temp = calTemp.getTime().compareTo(calendar.getTime());
if(temp > 0){
}else{
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent1);
}
here calTemp gives current time and calender gives the time i want to fire the alarm. So according to above code if the time has already past then the notification will not fire for sure .
Hi I've had the same problem and found a solution in this SO post, basically the idea is to rely on AlarmManager, Receiver but avoid usage of Service.
Since you are using the Service just to build and display the notification you may find useful my approach.
Let me know.

Service in android crashes after several hours

i tried to write a simple service for an android device. it looks like
public void onReceive(Context context, Intent intent) {
// do something
// new alarm
setNextAlarm(context);
}
public static void setNextAlarm(Context context) {
Intent myIntent = new Intent(context, MainReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// trigger
Calendar cal = Calendar.getInstance();
// here is possible that trigger time will be different by each call
long triggerTime = computeNextTriggerTime();
long triggerAtTime = cal.getTimeInMillis() + triggerTime;
alarmManager.setInexactRepeating(AlarmManager.RTC, triggerAtTime, triggerTime, pendingIntent);
}
Well, I noticed that it works, but sometimes it crashes after days or hours of using and I'm quite sure, that it is not because of the code, that do the logic and that I didn't post here.
The trigger time is between 10 and 30 minutes.
Every help will be appreciated :)

Categories

Resources