Cant get AlarmManager and broadcast working - android

No matter how I try, I cannot get the alarmManager and receiver to work - there seem to be SO many different ways to do it from what i've searched, but nothing seems to work.
I have in Manifest:
<receiver android:name="AlarmReceiver" />
I am using inner class for broadcastReceiver:
private class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("ALARM","TRIGGERED");
Notification(filteredList.get(0).getTitle());
}
}
I call function SetAlarm to start the manager:
private void SetAlarm(long time) {
AlarmManager alarm_mgr = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
//PendingIntent pi = PendingIntent.getService(MainActivity.this, 0, intent, 0);
PendingIntent pi = PendingIntent.getBroadcast(this, 111, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
alarm_mgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
Log.d("ALARMSET", "Alarm " + calendar.getTime().toString());
}
As you can see, in the receiver I have a notification call - I won't post because I know this works, but there is also a log that is not working.
For testing purposes I've set time to current time using the Calendar function.
You can see the pendingIntent, i have tried both getService and getBroadcast, I can't figure out which I need, but neither works anyway.
I'm sure I'm missing something, i don't know what, and I can't seem to find any answers at Google.
Is the AlarmReceiver ok as an inner class ? I have put it there because I need access to my "filteredList" List object.
thx

I am using inner class for broadcastReceiver:
This will not work. Android has to be able to create an instance of your BroadcastReceiver, and it cannot do so. At best, your BroadcastReceiver could be a static nested class, but then you would have to fix your manifest entry to refer to the outer class:
<receiver android:name="OuterClass$AlarmReceiver" />

No, actually the BroadcastReceiver needs to be public.Only then you can register it in manifest and access them. Place the AlarmReceiver code in a separate .java file. You will see the log inside the BroadcastReceiver.

try this
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);
// Set the alarm to start at 8:30 a.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 30);
// setRepeating() lets you specify a precise custom interval--in this case,
// 20 minutes.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
For more details.. Look this

I stucked 1 day for this problem, and finally solved this.
AlarmManager is used to generate a broadcast every 30 seconds, and a broadcast receiver is used to receive the message and execute ...
So the main problem is the following 2 steps
1. In the AndroidManifist.xml a action filter needed.
<receiver android:name="com.istep.gps.straight.MyTimerReceiver">
<intent-filter>
<action android:name="com.istep.gps.straight.MyTimerReceiver.Action"/>
</intent-filter>
</receiver>
2. The most important is the Intent need to be empty, no AAA.class
private void initTimer(Context context) {
Intent intent = new Intent().setAction("com.istep.gps.straight.MyTimerReceiver.Action")
.putExtra("id",UniqueID.getID(context));
PendingIntent sender = PendingIntent.getBroadcast(context, 18, intent, 0);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000 * 30, sender);
}

When you use calendar, you should setTimeInMillis
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());

Related

Alarm Manager Android

private void startAlarm() {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 23);
calendar.set(Calendar.MINUTE, 52);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 20, alarmIntent);
}
startAlarm() method is in the MainActivity class.
The following code should display a toast (declared in onReceive() method of the AlarmReceiver class) at 23:52 and every 20 minutes thereafter
AlarmReceiver extends BroadcastReceiver.
The code compiles without errors but for some reason it is not displaying the toast.
NOTE : The code worked fine with ELAPSED_REALTIME_WAKEUP. I am having problem with RTC_WAKEUP only. So everything else has to be correct. There is something wrong inside the startAlarm() method only.
I have tried your code with some modification as below .
private void startAlarm() {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
alarmMgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 2);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 20, alarmIntent);
}
This code works fine with AlarmManager.RTC_WAKEUP. If it does not work for you, please reboot your device after installing it. After reboot completed, start your app. Then it should fire the alarm and every 20 sec interval the alarm fires repeatedly.
You can also check the difference between RTC_WAKEUP and ELAPSED_REALTIME_WAKEUP. From android docs, elapsedRealtime means, Returns milliseconds since boot, including time spent in sleep and RTC means, time in System.currentTimeMillis() (wall clock time in UTC).
Looks like You need to set an action to the intent:
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
intent.setAction("YourPackageName.YourAction");
alarmIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
And in the manifest:
<receiver android:name=".AlarmReciever">
<intent-filter>
<action android:name="YourPackageName.YourAction" />
</intent-filter>
</receiver>
This should fix the issue. You must have a unique action in the intent for use it with broadcast receiver.

Create alarm service in android for multiple times

in my task application, i want to create alarm service for multiple items. Here is the code i followed to create service. Lets assume, if there are more than 5 items present in list. then we will sent alarm service for 5 different times.
What if the user comes and edits the time?, how to update the system and make sure it triggers at new instance?. What if the user delete the task, how to quickly removes the registered alram for the deleted task?
What about uninstalling the app?, how to clear all the entries?, what if the system re-boots?
This is the code i'm following to register the task in alram services
Calendar Calendar_Object = Calendar.getInstance();
Calendar_Object.set(Calendar.MONTH, 8);
Calendar_Object.set(Calendar.YEAR, 2012);
Calendar_Object.set(Calendar.DAY_OF_MONTH, 6);
Calendar_Object.set(Calendar.HOUR_OF_DAY, 14);
Calendar_Object.set(Calendar.MINUTE, 25);
Calendar_Object.set(Calendar.SECOND, 0);
Step 2:
We need to create an alarm which help us to invoke the BroadCastReceiver on our specified time.
// MyView is my current Activity, and AlarmReceiver is the BoradCastReceiver
Intent myIntent = new Intent(MyView.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
MyView.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
/*
The following sets the Alarm in the specific time by getting the long value of the alarm date time which is in calendar object by calling the getTimeInMillis(). Since Alarm supports only long value , we're using this method.
*/
alarmManager.set(AlarmManager.RTC, Calendar_Object.getTimeInMillis(),
pendingIntent);
Use this method to set Alarm :
public static void startAlarm(Context context, int alarm_code, String time) {
String[] arrTime = time.split(":");
intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
PendingIntent mAlarmSender = PendingIntent.getBroadcast(context,
alarm_code, intent, 0);
Calendar cal_alarm = Calendar.getInstance();
cal_alarm.setTimeZone(TimeZone.getDefault());
cal_alarm.set(Calendar.HOUR_OF_DAY, Integer.parseInt(arrTime[0]));
cal_alarm.set(Calendar.MINUTE, Integer.parseInt(arrTime[1]));
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal_alarm.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, mAlarmSender);
}
Here,"int alarm_code" is your unique code for particular item.
And for update alarm first cancel the existing alarm and set new alarm for new time.For that use this method :
public static void cancelAlarm(Context context, int alarm_code) {
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlarmReceiver.class);
intent.putExtra("CODE", alarm_code);
am.cancel(PendingIntent.getBroadcast(context, alarm_code, intent, 0));
}
Here,"int alarm_code" will be your unique code which you have used to set alarm.So that alarm with particular alarm_id will be cancel.You can also delete alarm with this method.
Same way you can clear all the alarms passing alarm_code to the given function.
You have to register receiver for system reboot and in onReceive of register you have to set all alarms again.
Hope this will help you.

Android Alarm Manager doesn't work

So I have a BroadcastReceiver which looks like this:
public class UpdateReceiver extends BroadcastReceiver {
public UpdateReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
System.out.println("Broadcast received");
PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, System.currentTimeMillis(), cal.getTimeInMillis(), operation);
}
}
This is how I call the BroadcastReceiver
Intent in = new Intent ("REFRESH_BROADCAST");
sendBroadcast(in);
And this is my intent-filter in Android Manifest file
<service android:name = ".services.RefreshService">
<intent-filter>
<action android:name="REFRESH_THAT"/>
</intent-filter>
</service>
<receiver android:name=".services.UpdateReceiver">
<intent-filter>
<action android:name="REFRESH_BROADCAST"/>
</intent-filter>
</receiver>
BroadcastReceiver received a brodcast without any problem, but AlarmManager seems to do nothing. If I call operation.send() it works without a problem, so I presume there is something wrong with AlarmManager.
Alright so finally I found a solution a it was my fault.
I have set int type to AlarmManager.ELAPSED_REALTIME and long triggerAtMillis to System.currentTimeMillis() property of alarmManager.setInexactRepeating(.....) which is wrong, it only can be paired with AlarmManager.RTC / RTC_WAKEUP.
So the functional code is this:
PendingIntent operation = PendingIntent.getService(context, 0,new Intent("REFRESH_THAT"), 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() , 30000, operation);
I should really read API documentation more carefully. If you hover AlarmManager.ELAPSED_REALTIME , it will told you what kind of time trigger you have to use. Hope this my stupid mistake will help someone in future.
As per the setInexactRepeating doc, The third parameter is:
intervalMillis: interval in milliseconds between subsequent repeats of the alarm
Then you should put 10000 ms (which is 10 sec) instead of cal.getTimeInMillis()
alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME, cal.currentTimeMillis(), 10000, operation);
Which means that, youer alarm will go off after 10 sec of the intent firing, then will repeat each 10 sec. And of course, since you are using this method, This is inexact timing.

In android, is it possible to use more than one AlarmManager with different repeat values in a single application?

I'm developing an application for mobile and tablet using android 2.3**
I want to do some operations namely Operation-A and Operation-B. Both perform some pocess.
I want to repeat the Operation-A and Operation-B is performed every 1 hour time interval
Operation-A is performed before the 10 minutes of Operation-B
Operation-B is performed when the time is 0.00,1.00,2.00,3.00,....,23.00 (I'm using railway time. So it is not confused for am or pm).
Operation-A is performed when the time is 0.50,1.50,2.50,3.50,....,23.50
The above scenarios is possible in android or not.
All are give your ideas for the above scenarios.
I'm planning to use AlarmManager. AlarmManager is android system service. It is used to notify the application every 1 hour.
I plan to use an AlarmManager for Operation-A and another AlarmManager for Operation-B.
My doubt is ,In android is it possible to use more than one AlarmManager with different repeat values in a single application?
All your ideas are welcome.
Yes this task will done with help of AlarmManager with reperating functionality. First you need to create two receiver class which will receive events . and then need to setup repeating alarm .
private void setAlarm1()
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.HOUR, 1);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*60, pendingIntent);
}
private void setAlarm2()
{
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 50);
Intent intent = new Intent(this, AlarmReceiver_1.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
intent, PendingIntent.FLAG_CANCEL_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000*60*50, pendingIntent);
}
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
public class AlarmReceiver_1 extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
}
}
In menifest, you need to declare the classes as below.
<receiver android:name=".AlarmReceiver" />
<receiver android:name=".AlarmReceiver_1" />

Broadcast receiver not called

I know this a basic problem but it is still driving me crazy. I am setting a repeating alarm but the receiver is never called.
Intent intent = new Intent(NewSchedule.this, RepeatingAlarm.class);
PendingIntent sender = PendingIntent.getBroadcast(NewSchedule.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, calendar.getTimeInMillis(), 5 * 1000, sender);
Log.i("calendar",calendar.getTimeInMillis() + "");
Toast.makeText(NewSchedule.this, "repeating_scheduled", Toast.LENGTH_SHORT).show();
public class RepeatingAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "repeating_received", Toast.LENGTH_LONG).show();
}
}
<receiver android:name=".RepeatingAlarm" android:process=":remote" />
I am testing on my phone. The calendar log shows the exact time. I never get the Toast in the receiver class.
Reference : Android Alarm Manager with broadcast receiver
Intent sender = new Intent("WhatEverYouWant");
PendingIntent senderPIntent = PendingIntent.getBroadcast(context, 0, sender, 0);
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.set(AlarmManager.RTC_WAKEUP, triggerTime, senderPIntent);
// In Manifest.xml file
<receiver android:name="com.package.YourOnReceiver">
<intent-filter>
<action android:name="WhatEverYouWant" />
</intent-filter>
</receiver>
Actually it turned out my code was good. Somehow the alarm was up and running and thus for some unknown reason (at least to me) the recevier could not be called. I figured it out when I created a new project and tested that that receiver was working fine. I also had to stop that alarm. Then I went back to my original project and started the same alarm without changing any lines and it was working fine. Has anyone experienced this?

Categories

Resources