Android Give Notification on a specific day - android

I'm trying to build an app where I'm building a countdown timer to a specific date and time. Now I've built the countdown timer using the android countdown timer class and it's working properly.
Now what I want to do is show a notification method in the onFinish() of the Countdown Timer saying that the event has arrived. I want the notification to show even if the app isn't running. Here is my code so far:
new CountDownTimer(timer.getIntervalMillis(), 1000) {
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
int days = (int) ((millisUntilFinished / 1000) / 86400);
int hours = (int) (((millisUntilFinished / 1000) - (days * 86400)) / 3600);
int minutes = (int) (((millisUntilFinished / 1000)
- (days * 86400) - (hours * 3600)) / 60);
int seconds = (int) ((millisUntilFinished / 1000) % 60);
String countdown = String.format("%02d:%02d:%02d:%02d", days,
hours, minutes, seconds);
countdownTimer.setText(countdown);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
countdownBegins.setVisibility(View.GONE);
countdownTimer.setText("SYMAGINE IS HERE!!");
}
}.start();
How do I show a notification when the countdown timer has finished. Even at the chance that the app may not be running. I've seen AlarmManager but somehow i didn't understand it. Help is appreciated with proper explanation since i'm kind of a newbie.

You should use android AlarmManager. When you Schedulle an alarm with it, it will trigger the event( it doesnt matter if your app is running or not, it will trigger the event ).
Since you want to show a notification i would suggest that you start a Service when the alarm triggers, and build your notification from the service.
Take a look at this: http://www.techrepublic.com/blog/software-engineer/use-androids-alarmmanager-to-schedule-an-event/
Here is an example : How to start Service using Alarm Manager in Android? --> it uses a repeating alarm but the logic is the same.
Try out a few examples and you will get the hold on of it, AlarmManager is actually very simple to use as you will see from the above examples.
Bellow example taken from : How to schedule a task using Alarm Manager
public void scheduleAlarm(View V)
{
// time at which alarm will be scheduled here alarm is scheduled at 1 day from current time,
// we fetch the current time in milliseconds and added 1 day time
// i.e. 24*60*60*1000= 86,400,000 milliseconds in a day
Long time = new GregorianCalendar().getTimeInMillis()+24*60*60*1000;
// create an Intent and set the class which will execute when Alarm triggers, here we have
// given AlarmReciever in the Intent, the onRecieve() method of this class will execute when
Intent intentAlarm = new Intent(this, AlarmReciever.class);
//Get the Alarm Service
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//set the alarm for particular time
alarmManager.set(AlarmManager.RTC_WAKEUP,time, PendingIntent.getBroadcast(this,1, intentAlarm, PendingIntent.FLAG_UPDATE_CURRENT));
Toast.makeText(this, "Alarm Scheduled for Tommrrow", Toast.LENGTH_LONG).show();
}
AlarmReciever Class
public class AlarmReciever extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
// Your Code When Alarm will trigger
}
}

Related

Understanding My AlarmManager Logic

I need help in understanding the logic that I have implemented in my app using AlarmManager, since the logic is not working as I expected. I am new to Android development and a self-learner.
The Logic :
User selects a time in Main Activity using a button.
That time value is used for setting repeating alarm in Another activity.
When the alarm goes of A dialog box appears.
Main Activity:
static long ATfrom_to_millisec;
case R.id.ATfrom:
final Calendar ATfromC = Calendar.getInstance();
ATfromHour = ATfromC.get(Calendar.HOUR_OF_DAY);
ATfromMinute = ATfromC.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog ATfromtpd = new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Converting to milli seconds to use in AlarmManager
ATfrom_to_millisec = ((hourOfDay * 60 * 60 * 1000) + (minute * 60 * 1000));
String AM_PM;
if (hourOfDay < 12) {
AM_PM = "AM";
} else {
AM_PM = "PM";
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
}
}
if (minute < 10) {
ATfrom.setText(hourOfDay + ":0" + minute + " " + AM_PM);
} else {
ATfrom.setText(hourOfDay + ":" + minute + " " + AM_PM);
}
In the above logic the time selected by the user is converted to milliseconds and stored in a public static variable so that it can be used by other activities.
Alarm Activity :
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()){
case R.id.bReminder:
try {
//Receiving the static variable's value from MainActivity
long AT_from = MainActivity.ATfrom_to_millisec;
float cov = (float)(AT_from/1000/60/60);
//Toast to check if the time value is passed correctly
toast.makeText(getApplicationContext(), String.valueOf(cov), toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Notifier.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this.getApplicationContext(),
12345, intent, 0);
//Logic for Repeating Alarm that uses the time value from MainActivty as starting time and repeating it every 10 seconds.
// i.e. the alarm should go off after 10 seconds from the use selected time and repeat after 10 seconds.
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, AT_from + (10*1000), 10*1000, pendingIntent);
} catch (Exception e) {}
break;
case R.id.bReminderStop:
AlarmManager am =
(AlarmManager)getSystemService(Activity.ALARM_SERVICE);
am.cancel(pendingIntent);
break;
}
}
When alarm is set with the above implemented logic , The alarm goes of immediately once it is set and repeats with an interval of 1 minute.
But I implemented my logic expecting the alarm to go of 10 seconds from the time set by user and repeat after every 10 seconds
I am not able to understand the mistake implemented in my logic.
Also in the toast I am not getting the decimal value of float cov
(eg : 11:30 PM must be displayed as 23.5 .But it is displayed as 23.0)
Dialog Activity when Alarm goes off :
public class Notifier extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setTitle("HydrateTime");
alertDialogBuilder.setMessage("Enter the amount of water");
alertDialogBuilder.setPositiveButton("Update", null);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
}
I want the above Activity to be invoked when the Alarm goes off. Is the above implemented logic enough to make a Dialog window appear when an activity goes of?
Note : I am using a general activity definition in the Android Manifest.
like :
<activity
android:name=".Notifier"
android:label="#string/app_name">
</activity
Kindly request answers for the below questions :
Am I passing the time value set in the MainActivity to the AlarmManager in another activity correctly?
What is the mistake in my Alarm logic and how to rectify it such that the alarm goes of as per my requirement?
Is the definition for the dialog box correct? should there any more definitions in Manifest? should I create any layout file for the dialog activity? Should I extend my Notifier class with Dialog class instead of Activity class?
The logic has a minor flaw. You see, with alarms if the time to fire has already passed, then the alarm will fire immediately. For eg: if I set an alarm with milli seconds for 2 Jan 1983, it would fire immediately. If you notice, you are doing something similar.
To fix it, simply add this in your Alarm Activity:
// Will trigger after 10 secs from set time
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + AT_from + (10*1000), 10*1000, pendingIntent);
I am not sure what is causing the interval problem though. It seems fine to me.

How to add adding "remind me after half an hour" functionality - android

I have done an application that fire an alarm in certain time, and i am stuck on implementing remind me after half an hour functionality
what can i do to implement receiver, or service or anything that runs after half an hour of clicking the button of reming me after half an hour
any suggestions ?
Edited the code from Android execute a function after 1 hour to half an hour.
// the scheduler
protected FunctionEveryHalfHour scheduler;
// method to schedule your actions
private void scheduleEveryHalfHour(){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
new Intent(WAKE_UP_AFTER_HALF_HOUR),
PendingIntent.FLAG_UPDATE_CURRENT);
// wake up time every 1 hour
Calendar wakeUpTime = Calendar.getInstance();
wakeUpTime.add(Calendar.SECOND, 30 * 60);
AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
aMgr.set(AlarmManager.RTC_WAKEUP,
wakeUpTime.getTimeInMillis(),
pendingIntent);
}
//put this in the creation of service or if service is running long operations put this in onStartCommand
scheduler = new FunctionEveryHalfHour();
registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_HALF_HOUR));
// broadcastreceiver to handle your work
class FunctionEveryHalfHour extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// if phone is lock use PowerManager to acquire lock
// your code to handle operations every half hour...
// after that call again your method to schedule again
// if you have boolean if the user doesnt want to continue
// create a Preference or store it and retrieve it here like
boolean mContinue = getUserPreference(USER_CONTINUE_OR_NOT);//
if(mContinue){
scheduleEveryHalfHour();
}
}
}
You can write a simple service with a timer and whenever the time is up.it can do your thing.all you need to do is start a service with a timer inside of it

Calendar, execute code every 24 hours

I would like to execute a piece of code every 24 Hours however I'm not sure how to do this.
I have some code that sets the time that I would like the cycle to start but not sure how to execute the end time
int startDay = 00; // 12am
int end = 24; // 12 pm
int hours = (end - startDay) % 24; //difference will be 24 hours
Calendar calInstanceOne = Calendar.getInstance();
// set calendar to 12 am
calInstanceOne.set(Calendar.HOUR_OF_DAY, startDay);
calInstanceOne.set(Calendar.MINUTE, 0);
calInstanceOne.set(Calendar.SECOND, 0);
calInstanceOne.set(Calendar.MILLISECOND, 0);
Do I create another Calendar instance, set to 12pm? and compare the two? Would really appreciate any insight into this.
I would like to execute a piece of code every 24 Hours
Use AlarmManager, in conjunction with either WakefulBroadcastReceiver or my WakefulIntentService. Ideally, use setInexactRepeating() on AlarmManager for INTERVAL_DAY, to allow Android to slide the actual time around to best save battery for the user.
You can use AlarmManager to make actions periodically:
Intent intent = new Intent(this, MyStartServiceReceiver.class).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 5000, <24h in msecs>, pendingIntent);
Then you should register your BroadcastReceiver in the manifest and call the method you want to execute from this receiver.
First store your current time then whenever app will be open compare current time with previous store time if its greater or equal 24 hour
execute your code.
You may have several choices, let me outline the easiest one. The strategy is to simply use the system time to execute twenty four hours later:
package com.test;
import java.util.Calendar;
public class ExecuteCheck {
//Class fields
/* Number of milliseconds in a day
*
*/
private static final long C_DAY=24*60*60*1000;
//Object fields
/* Time last executed (or beginning of cycle), in milliseconds;
*
*/
private long lastExecuted = System.currentTimeMillis();
public ExecuteCheck() {
}
/** Set the current execution cycle time to now
*
*/
public void setExecutionTimeToNow() {
lastExecuted = System.currentTimeMillis();
}
/** Set the execution cycle time to be the value in the calendar argument.
* #param cal
*/
public void setExecutionTime(Calendar cal) {
lastExecuted = cal.getTimeInMillis();
}
/** Is it more than twenty-four hours since the last execution time?
* #return
*/
public boolean isTimeToExecute() {
return (System.currentTimeMillis() - lastExecuted) > C_DAY;
}
}

how can I pick an incoming call in android?

I am developing an android app and want to know how can I receive an incoming call.
I have created a broadcast receiver and in its on receive method I have given a 15 second delay using countdown timer on call state ringing.Now, I want to receive an incoming call in countdown timer's finish method. I am not getting any way to implement it. can anyone suggest ?
thanks!!
instead of using a countdown timer, set a one-time Alarm instead which then fires your method to receive the call. You can do something like this:
AlarmManager alarm = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent cHandler = new Intent (this, CallHandlers.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, cHandler, PendingIntent.FLAG_CANCEL_CURRENT);
//Set an alarm that will trigger in 15 seconds
alarm.set(AlarmManager.RTC_WAKEUP,System.currentTimeMillis() + (15 * 1000), pi);
hi you can use a coundowntimer visit http://developer.android.com/reference/android/os/CountDownTimer.html
new CountDownTimer(15000, 1000) {
public void onTick(long millisUntilFinished) {
//here you can have your logic for call
}
public void onFinish() {
mTextField.setText("done!");
}
}
.start();
for working code example of countdowntimer visit http://www.filefactory.com/file/cbbbc38/n/SimpleCountDownTimerExample.zip

I want to schedule task at particular time for different day(Monday, Tuesday, etc) in android

Currently I am working on BroadcastReceiver, Service & AlarmManager in Android to developed one of functionality in my project. I need to schedule some task at particular time on particular day.
For E.g :-
Monday - 09:00 AM & 05:00 PM
Tuesday - 09:00 AM & 05:00 PM
Wednesday - 09:00 AM & 05:00 PM
Thursday - 09:00 AM & 05:00 PM
Friday - 09:00 AM & 05:00 PM
Saturday - 10:00 AM & 10:00 PM
Sunday - 10:00 AM & 10:00 PM
What i have done till now is created one activity & broadcastreceiver. On click of button, after every 60seconds broadcast receiver will be called. Here is my code snippet. But i want to schedule my task according to the week that i have described above. Can anyone please kindly help me how can i schedule the task like above.
Code :-
public class AlarmDemoActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonStart = (Button)findViewById(R.id.start);
buttonStart.setOnClickListener(new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(getBaseContext(),
MyScheduledReceiver.class);
PendingIntent pendingIntent
= PendingIntent.getBroadcast(getBaseContext(),
0, myIntent, 0);
AlarmManager alarmManager
= (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
long interval = 60 * 1000; //
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), interval, pendingIntent);
finish();
}});
}
}
BroadcastReceiver :-
public class MyScheduledReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
/*Intent scheduledIntent = new Intent(context, MyScheduledActivity.class);
scheduledIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(scheduledIntent);*/
System.out.println("Make Phone Silent");
}
}
All suggestion and tips are welcomed.
I will give the idea for this at a very high level.You will have to figure out the coding your self:
1.Save the user preferences in shared preferences(which I presume you are already doing)
2.Schedule the first alarm using the set method of Alarm Manager
Refer this for details on this method.
3.When that alarm goes off,again schedule the next alarm using the next time period in Shared Preferences,again using the set method
You don't need to call it every 60 seconds, you can set the time when it should be fired into an alarm using your calendar instance and setting the correct dates, so alarm manager will fire the broadcast intent at specified dates and times.
Beware that if the phone is turned of the alarm manager will be reset so you have to store the alarms in any persistent storage and register a broadcast receiver for the BOOT_COMPLETED action to restore the alarms.
You can test with small intervals so you won't have to wait the whole day :)

Categories

Resources