Making an alarm program - not working - android

I am attempting to make alarm program. So far I have written an activity in which the user can select the time he wishes the alarm to go off. This is working fine. Now I need to use the alarm manger to tell the OS to call some of my code at a certain point in the future. Just to test this in a crude way I added the following code that gets executed when I press a test button in my main activity:
Intent intent = new Intent(getApplicationContext(), to_call_when_alarm_goes_off.class);
PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.cancel(pIntent);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()+1000,
AlarmManager.INTERVAL_DAY,
pIntent);
This should mean that some code called to_call_when_alarm_goes_off will get executed one second after I press the button.... Now this is where I'm a little confused. I'm not sure quite how/where to set up "to_call_when_alarm_goes_off". What I did was simply add a new class to my project as follows:
package com.mycompany.alarmprogram;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class to_call_when_alarm_goes_off extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent arg1)
{
// TODO Auto-generated method stub
Log.i("ALARM","TIME TO WAKE UP!!!");
}
}
All the code compiles, and when I press the button all the code in the first code snippet gets executed without crashing - but one second later the broadcast receiver code is not executed. Clearly I am misunderstanding something.

I assume you are missing registering your receiver in Manifest file, With appropriate action string. as given below.
<receiver android:name=".to_call_when_alarm_goes_off" >
<intent-filter>
<action android:name="com.android.whatever.WHAT_EVER_NAM_YOU_WANNA_GIVE" />
</intent-filter>// can change name/action string as par ur requirement.
</receiver>
you need to set same action string in your intent, Remember Action string must be same in Manifest and here intent.setAction("com.android.whatever.WHAT_EVER_NAM_YOU_WANNA_GIVE"); in java also. then only it will tringger receiver.
Your code can be changed like given below.
Intent intent = new Intent(getApplicationContext(), to_call_when_alarm_goes_off.class);
intent.setAction("com.android.whatever.WHAT_EVER_NAM_YOU_WANNA_GIVE");// added line
PendingIntent pIntent = PendingIntent.getBroadcast(getApplicationContext(),0, intent, 0);
AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarms.cancel(pIntent);
alarms.setRepeating(
AlarmManager.RTC_WAKEUP,
System.currentTimeMillis()+1000,
AlarmManager.INTERVAL_DAY,
pIntent);

You need to register to_call_when_alarm_goes_off class in AndroidManifest.xml as receiver:
<receiver android:name=".to_call_when_alarm_goes_off"></receiver>
See details in API docs.

Related

Schedule an alarm on device reboot automatically in android

I am trying to build an application which checks for notification files on a server, every hour. I used the alarm manager class to implement this. But I am unable to implement the automatic start on reboot part. I want that the alarm should run periodically after reboot. Can some one please tell me how to go about doing it.
This is my MyAlarmReceiver Class.
package com.example.quickstart;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
public class MyAlarmReceiver extends BroadcastReceiver {
public static final int REQUEST_CODE = 12345;
public static final String ACTION = "com.example.quickstart.alarm";
// Triggered by the Alarm periodically (starts the service to run task)
#Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, NotificationService.class);
// i.putExtra("username", username);
context.startService(i);
}
}
This is my NotificationBootReceiver Class.
package com.example.quickstart;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class NotificationBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Construct an intent that will execute the AlarmReceiver
Intent i = new Intent(context, MyAlarmReceiver.class);
// Create a PendingIntent to be triggered when the alarm goes off
final PendingIntent pIntent = PendingIntent.getBroadcast(context, MyAlarmReceiver.REQUEST_CODE,
i, PendingIntent.FLAG_UPDATE_CURRENT);
// Setup periodic alarm every every half hour from this point onwards
long firstMillis = System.currentTimeMillis(); // alarm is set right away
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// First parameter is the type: ELAPSED_REALTIME, ELAPSED_REALTIME_WAKEUP, RTC_WAKEUP
// Interval can be INTERVAL_FIFTEEN_MINUTES, INTERVAL_HALF_HOUR, INTERVAL_HOUR, INTERVAL_DAY
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
2*60*60,pIntent);
// alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, firstMillis,
// AlarmManager.INTERVAL_FIFTEEN_MINUTES, pIntent);
}
}
AndroidManifest file looks like this(it's not the complete manifest file but the relevant parts)
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".NotificationBootReceiver"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>
The notifications are working fine, but what I want is the start notifications automatically on reboot feature. When i reboot the notification feature does not work,i.e, the alarm does not go off. And also the android documentation says (this only works if the app has already been launched by the user at least once) , is there a way to set the alarm automatically on reboot without launching the app. Any help appreciated. Thanks in advance
Documentation link android devs link
(Go to: Start an alarm when the device restarts)
No it isn't possible to set the alarms without starting the app even once. Once the app has been started the alarms can be triggered.

AlarmManager alarm start when system time is changed by user?

i am using AlarmManager class for setting Alarms it is working fine.
But if i set alarm like 9pm and current time is 8pm and i changed the system time to 10pm
then alarm 9pm alarm start automatically. so to solve this issue
i have searched so much but did not found any good answer
Please help
here is my code for alarm setting
final int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("requestCode", id);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 2*60*1000, pendingIntent);
One of the options is to store all set alarms in database, then create a BroadcastReceiver which will listen for ACTION_TIME_CHANGE action. When user changes time it will be triggered. Then create a IntentService which will be responsible for resetting alarms. In this service class:
Read db and identify all passed alarms.
Cancel passed alarms
Set alarms for next day
Your code may look like as below:
In your Manifest:
<uses-permission android:name="android.permission.ACTION_TIME_CHANGE"/>
and below activities:
<receiver android:name=".TimeChangedReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>
<service android:name=".RestartAlarmsService"/>
Create class "TimeChangedReceiver" inside of which:
public class TimeChangedReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if("android.intent.action.TIME_SET".equals(intent.getAction())) {
Intent i = new Intent(context, RestartAlarmsService.class);
ComponentName service = context.startService(i);
}
}
}
Create "RestartAlarmsService" class inside of which:
public class RestartAlarmsService extends IntentService {
public RestartAlarmsService() {
super("RestartAlarmsService");
}
#Override
protected void onHandleIntent(Intent intent) {
// read db here
// then cancel passed alarms
// reset them to next day
}
}
You can find many tutorials on how to use Databases and implement it in your code. Hope my answer is somehow helpful.
yes it will give you broadcast, as your pending intent object is still attached to that event while you change time that is greater than you alarm firing time.
solution- validate your condition while you receive broadcast from alarm manager

How to run a service every day at noon, and on every boot

In my app I have SQLite database that has one table with date rows in milliseconds. I would like to have a notification shown every day IF 30 days has passed since the last date value stored in my database. A service seems to be a good way to accomplish this check up.
I ran into Commonsware's WakefulIntentService and thought it could be the answer but I really don't know how should I implement it. In the demo it starts a service after 5 minutes since boot is complete which is just fine but what do I need to add to get it also start at every noon. (... but only to show one notification / day, not both, as from boot and regular daily check up)
I know this could be solved using AlarmManager but really don't know how. So, the help I need is to give me some samples / key points to get the service start on every boot and/or every day without app running.
thanks
Android alarmmanager is your answer. use it with a broadcast receiver which also resets the alarms on phone wake.
Now with code example:
Setting alarm inside a method:
Intent intent = new Intent(context, AlarmReceiver.class);
intent.setAction("packagename.ACTION");
PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pendingIntent);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
Receiver for your interval:
public class AlarmReceiver extends BroadcastReceiver {
private final String SOMEACTION = "packagename.ACTION"; //packagename is com.whatever.www
#Override
public void onReceive(Context context, Intent intent) {
Time now = new Time();
now.setToNow();
String time = FileHandler.timeFormat(now);
String action = intent.getAction();
if(SOMEACTION.equals(action)) {
// here you call a service etc.
}
Receiver for resetting alarms whenever phone has been shut down.
public class AlarmSetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// get preferences
SharedPreferences preferences = context.getSharedPreferences("name_of_your_pref", 0);
Map<String, ?> scheduleData = preferences.getAll();
// set the schedule time
if(scheduleData.containsKey("fromHour") && scheduleData.containsKey("toHour")) {
int fromHour = (Integer) scheduleData.get("fromHour");
int fromMinute = (Integer) scheduleData.get("fromMinute");
int toHour = (Integer) scheduleData.get("toHour");
int toMinute = (Integer) scheduleData.get("toMinute");
//Do some action
}
}
}
Manifest very important, this is added under application:
<receiver android:name="AlarmReceiver">
<intent-filter>
<action android:name="packagename.ACTION"/>
<action android:name="packagename.ACTION2"/>
</intent-filter>
</receiver>
<receiver android:name="AlarmSetter" >
<intent-filter>
<action
android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
Also in order for this to work you need to add permission to receive the boot Broadcast in the manifest with following line:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
Hope this cleared things up, if any errors plz tell.
Edit (added alarmsetter example):
public class AlarmSetter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do your stuff
}
}
This answer seems pretty old.
Now, I would totally recommend people to check out SyncAdapter framework provided by Google.
It is custom made for such things.
Here's the link: https://developer.android.com/training/sync-adapters/index.html
In the demo it starts a service after 5 minutes since boot is complete which is just fine but what do I need to add to get it also start at every noon.
Change the initial time of the setRepeating() call. The example shows one minute from now -- you would need to do the calculations to determine when the next noon is.
You can see an example of that sort of calculation in this OnBootReceiver from a different sample project. Here, I am setting up the alarm to go off every day at a user-specified time.

How do you start an Activity with AlarmManager in Android?

I've poured through a dozen tutorials and forum answers about this problem, but still haven't been able to get some working code together. I'll try to keep the question straightforward:
How do you use AlarmManager (in the Android API) to start an Activity at a given time? Any solution to this problem will do.
My latest attempt to achieve this is below.
(Imports omitted. I expect MyActivity to start 3 seconds after the program is opened, which it doesn't. There are no error messages to speak of.)
public class AndroidTest2Activity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context context = this;//.getApplicationContext();
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); // CORRECT
Intent intent = new Intent(context, myReceiver.class); // CORRECT
PendingIntent pending = PendingIntent.getBroadcast( context, 0, intent, 0 ); // CORRECT
manager.set( AlarmManager.RTC, System.currentTimeMillis() + 3000, pending ); // CORRECT
setContentView(R.layout.main);
}
}
public class myReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Intent i=new Intent(context, myActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
public class myActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("", "Elusive success");
setContentView(R.layout.main);
}
}
Any advice would be appreciated.
Please note: I've got myReceiver in the manifest already
In case someone else stumbles upon this - here's some working code (Tested on 2.3.3 emulator):
public final void setAlarm(int seconds) {
// create the pending intent
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
// intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0,
intent, 0);
// get the alarm manager, and scedule an alarm that calls the receiver
((AlarmManager) getSystemService(ALARM_SERVICE)).set(
AlarmManager.RTC, System.currentTimeMillis() + seconds
* 1000, pendingIntent);
Toast.makeText(MainActivity.this, "Timer set to " + seconds + " seconds.",
Toast.LENGTH_SHORT).show();
}
public static class AlarmReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
Log.d("-", "Receiver3");
}
}
AndroidManifest.xml:
<receiver android:name="com.example.test.MainActivity$AlarmReceiver" >
</receiver>
Issues with BenLambell's code :
EITHER:
Move the receiver to it's own .java file or
make the inner class static - so it can be accessed from outside
Receiver is not declared correctly in the manifest:
if it's an inner class in MainActivity use:
<receiver android:name="package.name.MainActivity$AlarmReceiver" ></receiver>
if it's in a separate file:
<receiver android:name="package.name.AlarmReceiver" ></receiver>
If your intention is to display a dialog in the receiver's onReceive (like me): that's not allowed - only activities can start dialogs. This can be achieved with a dialog activity.
You can directly call an activity with the AlarmManager:
Intent intent = new Intent(MainActivity.this, TriggeredActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
((AlarmManager) getSystemService(ALARM_SERVICE)).set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + seconds * 1000, pendingIntent);
How do you use AlarmManager (in the Android API) to start an Activity at a given time?
Supply a PendingIntent to the set() call that identifies the activity to start up. Or, do what you're doing, which should work just fine.
This sample project is a bit elaborate, because it's 19 tutorials deep into one of my books, but if you look at classes like EditPreferences, OnBootReceiver, and OnAlarmReceiver, you will see the same basic recipe that you're using above. In this case, I could have just used a getActivity() PendingIntent, but the tutorial after this one gives the user a choice of launching an activity or displaying a Notification, so a BroadcastReceiver makes more sense.
Look for warnings in addition to errors in LogCat. Most likely, your receiver or activity is not in your manifest.
Note that popping up an activity out of the middle of nowhere is generally not a good idea. Quoting myself from the book in question:
Displaying the lunchtime alarm via a full-screen activity certainly works,
and if the user is looking at the screen, it will get their attention. However,
it is also rather disruptive if they happen to be using the phone right that
instant. For example, if they are typing a text message while driving, your
alarm activity popping up out of nowhere might distract them enough to
cause an accident. So, in the interest of public safety, we should give the user an option to
have a more subtle way to remind them to have lunch.
add this in your android mainifest file and it will hopefully work
<activity android:name=".MyReceiver" />
<receiver android:name=".MyReceiver"> </receiver>
In my experience you can achieve this without broadcast receiver, just use PendingIntent.getActivity() instead of getbroadcast()
private void setReminder(){
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar startTime = Calendar.getInstance();
startTime.add(Calendar.MINUTE, 1);
Intent intent = new Intent(ReminderActivity.this, ReminderActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(ReminderActivity.this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC, startTime.getTimeInMillis(), pendingIntent);
}
I've tested this code on android O but I'm not sure about other android versions please inform me if this doesn't work on any other android version.
Main Problem : if you close completely you're app and expect to start you're activity after 3 seconds, you wrong. because when you close you're app , you're app cant receive broadcast, for solve this problem use services instead of broadcasts.
Point: when you're service would ran ,you cant start your activity if your app wouldn't in foreground.
Solution: I think when your service started you can again set Alarmmanager to start your activity with PendingIntent for just now.
Remember :
When you create your intent for pass it to pendingIntent add the FLAG_ACTIVITY_NEW_TASK to it.
For this PendingIntent use PendingIntent.getActivity() method and for the first PendingIntent use PendingIntent.getService() method.
I hope this help you.
I had this problem too long ago to know which answer is correct, but thank you to everyone for their responses. I'm self-answering so the question isn't still open.
According to Java convention class name begin with Capital letter.So change your
"myReceiver" to "MyReceiver" and "myActivity" to "MyActivity".
Then add your receiver in the manifest file like the below.
<application
------------
<receiver android:name="MyReceiver"></receiver>
---------------------
</application>
you are not sending any broadcast for the receiver to receiver and further more it lokks like u want a splash screen or something like that for that purpose u can start a new thread wait for some sec then start ur activity in that and for that time period u can do what ever u want on the UI thread ...

Start app at a specific time

I was wondering if it's possible (and if it is how) to start up my app at a specific time, something like an alarmclock which goes off at a specific time.
Let's say I want my app to start up at 8 in the morning, is that feasable ?
You can do it with AlarmManager, heres a short example. First you need to set the alarm:
AlarmManager am = (AlarmManager) con.getSystemService(Context.ALARM_SERVICE);
Date futureDate = new Date(new Date().getTime() + 86400000);
futureDate.setHours(8);
futureDate.setMinutes(0);
futureDate.setSeconds(0);
Intent intent = new Intent(con, MyAppReciever.class);
PendingIntent sender = PendingIntent.getBroadcast(con, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
am.set(AlarmManager.RTC_WAKEUP, futureDate.getTimeInMillis(), sender);
Next, You need to create a reciever with some code to execute your application: (ie- starting your app):
public class MyAppReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
startActivity(new Intent(context, MyAppMainActivity.class));
}
}
You are probably looking for AlarmManager, which let's you start services / activities / send broadcasts at specific intervals or a given time, repeating or not. This is how you write memory friendly background services in android. AlarmManager is sort of like cron in unix. It allows your background service to start, do its work, and get out of memory.
You probably do not want to start an activity (if that's what you meant by "application"). If you want to alert the user that something has happened, add an alarm that starts a receiver at a given time, and have the receiver add a notification. The notification can open the application when clicked. That's less invasive than bringing some potentially unwanted activity to the foreground.
there is a very good tutorial: http://www.javacodegeeks.com/2012/09/android-alarmmanager-tutorial.html
here is the c&p:
Android AlarmManager tutorial
by Rakesh Cusat on September 20th, 2012 | Filed in: Android Core
While writing an application, need arises to schedule execution of code in future. You may require AlarmManager to schedule your work at a specified time. AlarmManager accesses to system alarm and schedules the execution of code even when the application is not running.
Project Information: Meta-information about the project. Platform Version : Android API Level 10.
IDE : Eclipse Helios Service Release 2
Emulator: Android 4.1
Prerequisite: Preliminary knowledge of Android application framework, and Intent Broadcast receiver.
AlarmManager:
AlarmManager has access to the system alarm services. With the help of AlarmManager you can schedule execution of code in future. AlarmManager object can’t instantiate directly however it can be retrieved by calling Context.getSystemService(Context.ALARM_SERVICE). AlarmManager is always registered with intent. When an alarm goes off, the Intent which has been registered with AlarmManager, is broadcasted by the system automatically. This intent starts the target application if it is not running. It is recommended to use AlarmManager when you want your application code to be run at a specific time, even if your application is not currently running. For other timing operation handler should be used because it is easy to use. Handler is covered in other tutorial.
Method Description
set() Schedules an alarm for one time.
setInexactRepeating() Schedules an alarm with inexact repeating. Trigger time doesn’t follow any strict restriction.
setRepeating() Schedules an alarm with exact repeating time.
setTime() Sets the system’s wall clock time.
setTimeZone() Sets the system’s default time zone.
Check out the AlarmManager documention for more info.
In this tutorial let’s learn to create one-time timer and the repeating timer, and also to cancel the repeating timer. Here timer and alarm have been used interchangeably, but in this tutorial context both of them have the same meaning.
Example Code:
Let’s create three buttons start repeating timer, cancel repeating timer and one-time timer in the layout file. These buttons are attached with methods i.e startRepeatingTimer, cancelRepeatingTimer and onetimeTimer respecitively. These methods will be defined in the Activity class. The layout file is shown below(activity_alarm_manager.xml).
<linearlayout android:layout_height='match_parent'
android:layout_width='match_parent' android:orientation='vertical'
xmlns:android='http://schemas.android.com/apk/res/android'
xmlns:tools='http://schemas.android.com/tools'>
<button android:id='#+id/btStart' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='startRepeatingTimer'
android:padding='#dimen/padding_medium' android:text='#string/btStart'
tools:context='.WidgetAlarmManagerActivity'/>
<button android:id='#+id/btCancel' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='cancelRepeatingTimer'
android:padding='#dimen/padding_medium' android:text='#string/btCancel'
tools:context='.WidgetAlarmManagerActivity'/>
<button android:id='#+id/btOneTime' android:layout_height='wrap_content'
android:layout_width='match_parent' android:onclick='onetimeTimer'
android:padding='#dimen/padding_medium' android:text='#string/btOneTime'
tools:context='.WidgetAlarmManagerActivity'/>
</linearlayout>
We are going to define the BroadcastReciever which handles the intent registered with AlarmManager. In the given class onReceive() method has been defined. This method gets invoked as soon as intent is received. Once we receive the intent we try to get the extra parameter associated with this intent. This extra parameter is user-defined i.e ONE_TIME, basically indicates whether this intent was associated with one-time timer or the repeating one. Once the ONE_TIME parameter value has been extracted, Toast message is displayed accordingly. Helper methods have also been defined, which can be used from other places with the help of objects i.e setAlarm(), cancelAlarm() and onetimeTimer() methods. These methods can also be defined somewhere else to do operation on the timer i.e set, cancel, etc. To keep this tutorial simple, we have defined it in BroadcastReceiver.
setAlarm(): This method sets the repeating alarm by use of setRepeating() method. setRepeating() method needs four arguments:
type of alarm,
trigger time: set it to the current time
interval in milliseconds: in this example we are passing 5 seconds ( 1000 * 5 milliseconds)
pending intent: It will get registered with this alarm. When the alarm gets triggered the pendingIntent will be broadcasted.
cancelAlarm(): This method cancels the previously registered alarm by calling cancel() method. cancel() method takes pendingIntent as an argument. The pendingIntent should be matching one, only then the cancel() method can remove the alarm from the system.
onetimeTimer(): This method creates an one-time alarm. This can be achieved by calling set() method. set() method takes three arguments:
type of alarm
trigger time
pending intent
package com.rakesh.alarmmanagerexample;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.widget.Toast;
public class AlarmManagerBroadcastReceiver extends BroadcastReceiver {
final public static String ONE_TIME = 'onetime';
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 'YOUR TAG');
//Acquire the lock
wl.acquire();
//You can do the processing here.
Bundle extras = intent.getExtras();
StringBuilder msgStr = new StringBuilder();
if(extras != null && extras.getBoolean(ONE_TIME, Boolean.FALSE)){
//Make sure this intent has been sent by the one-time timer button.
msgStr.append('One time Timer : ');
}
Format formatter = new SimpleDateFormat('hh:mm:ss a');
msgStr.append(formatter.format(new Date()));
Toast.makeText(context, msgStr, Toast.LENGTH_LONG).show();
//Release the lock
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.FALSE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
//After after 5 seconds
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 5 , pi);
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
public void setOnetimeTimer(Context context){
AlarmManager am=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class);
intent.putExtra(ONE_TIME, Boolean.TRUE);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pi);
}
}
Given below is the manifest file. Here, WAKE_LOCK permission is required because the wake lock is being used while processing in onReceive() method present in AlarmManagerBroadcastReceiver class. AlarmManagerBroadcastReceiver has been registered as broadcast receiver.
<manifest android:versioncode='1' android:versionname='1.0'
package='com.rakesh.alarmmanagerexample'
xmlns:android='http://schemas.android.com/apk/res/android'>
<uses-sdk android:minsdkversion='10' android:targetsdkversion='15'/>
<uses-permission android:name='android.permission.WAKE_LOCK'/>
<application android:icon='#drawable/ic_launcher'
android:label='#string/app_name' android:theme='#style/AppTheme'>
<activity android:label='#string/title_activity_alarm_manager'
android:name='com.rakesh.alarmmanagerexample.AlarmManagerActivity'>
<intent-filter>
<action android:name='android.intent.action.MAIN'/>
<category android:name='android.intent.category.LAUNCHER' />
</intent-filter>
</activity>
<receiver android:name='com.rakesh.alarmmanagerexample.AlarmManagerBroadcastReceiver'>
</receiver>
</application>
</manifest>
Now let’s define the activity class which defines some methods. These methods are going to handle the button clicks. Here in this class we create an instance of AlarmManagerBroadcastReciever which will help us to access setAlarm(), cancelAlarm() and setOnetime(). Rest of the code is easy to understand.
package com.rakesh.alarmmanagerexample;
import com.rakesh.alarmmanagerexample.R;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
public class AlarmManagerActivity extends Activity {
private AlarmManagerBroadcastReceiver alarm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
alarm = new AlarmManagerBroadcastReceiver();
}
#Override
protected void onStart() {
super.onStart();
}
public void startRepeatingTimer(View view) {
Context context = this.getApplicationContext();
if(alarm != null){
alarm.SetAlarm(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
public void cancelRepeatingTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.CancelAlarm(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
public void onetimeTimer(View view){
Context context = this.getApplicationContext();
if(alarm != null){
alarm.setOnetimeTimer(context);
}else{
Toast.makeText(context, 'Alarm is null', Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_widget_alarm_manager, menu);
return true;
}
}
Once you are done with the coding, just execute the project and you will find the similar kind of application running in your emulator.
Please download https://github.com/rakeshcusat/Code4Reference/tree/master/AndroidProjects/AlarmManagerExamplecode, if you need reference code.
Reference: Tutorial on Android AlarmManager from our JCG partner Rakesh Cusat at the Code4Reference blog.
http://code4reference.com/2012/07/tutorial-on-android-alarmmanager/

Categories

Resources