Alarm manager triggered immediately - android

Hi I am currently working with AlarmManager. I have written a code given below. As per code the AlarmManager should be triggered after 10 Sec, but here in my code the alarm manager triggers immediately. Please help.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timeOrLengthofWait = 10000;
Intent intentToFire = new Intent(this, AlarmReciever.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);
alarmManager.set(alarmType, timeOrLengthofWait, alarmIntent);
}
}
And My AlarmReciever Class
public class AlarmReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String phoneNumberReciever="5556";
String message="Alarm Triggered";
SmsManager sms = SmsManager.getDefault();
sms.sendTextMessage(phoneNumberReciever, null, message, null, null);
Toast.makeText(context," A message has been sent", Toast.LENGTH_LONG).show();
Log.d("Alarm ", "Alarm Has been triggered and sms send");
}
}
I have Already added required permissions in manifest.

You are using an alarm type of ELAPSED_REALTIME_WAKEUP. That means that the second parameter to set() must be the number of milliseconds from now, where now is expressed as SystemClock.elapsedRealtime().
If your goal is to have this occur 10000 milliseconds from the time you make the set() call, that set() call should be:
alarmManager.set(alarmType, SystemClock.elapsedRealtime()+timeOrLengthofWait, alarmIntent);

If you are creating PendingIntent of an alarm for past time it will be fired immediately. Example - Schedule alarm for today 8AM but executing code around 11AM will fire immediately.
Solution:
cal.add(Calendar.DATE, 1);
long delay = 24 * 60 * 60 * 1000;
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), delay,pendingIntent);`
This will fire the event on next day at specified time (i.e 8AM);

Related

Multiple alarms are getting fired after reboot in android through broadcast receiver

I am making a notification application and for that i am using scheduled alarms for running the notifications using Broadcast receiver class and i am prompting user to select from daily or hourly notifications and i am defining both alarms in the same receiver under the same function and it is working fine but the problems comes when i restart my device,when i restart it both the alarms (daily and hourly) are getting triggered when i am only setting one for example if i set an alarm for 11:20 A.M and restart my device the hourly one and this 11:20 one both are getting triggered,i want that when i restart my device only the alarm which was selected before the device boot only gets triggered.
My receiver class:-
public class alarmreceiver extends BroadcastReceiver {
int id=0;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm running", Toast.LENGTH_SHORT).show();
start(context,id);
}
static void start(Context context,int id) {
Intent intent = new Intent(context, notification_receiver.class);
PendingIntent pendingintent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (id==1) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 11);
calendar.set(Calendar.MINUTE, 9);
calendar.set(Calendar.AM_PM, Calendar.AM);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingintent);
}
else
if (id==2) {
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 60 * 1000
, pendingintent);
}
}
I am calling this function under button click listener like this:-
For daily notifications:-
alarmreceiver.start(getApplicationContext(),1);
For hourly notifications:-
alarmreceiver.start(getApplicationContext(),2);
This code:
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime(), 60 * 1000, pendingintent);
sets a repeating alarm that goes off every minute, not every hour!
Also, this code sets an alarm that goes off right now and again every minute. The second argument to setRepeating() is the time of first alarm. You've passed SystemClock.elapsedRealtime() which basically means "now".

how can I set repeating alarm every 5 second to show message

here is my code in application class inside oncreate method: But I can't see any message from my app. Can anyone help me to do this?
Intent alarmIntent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
public void startAlarm() {
manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
int interval = 5000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
}
And on the broadcast receiver class I have the following code
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
// For our recurring task, we'll just display a message
Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();
}
}
Edited answer:
Use setInexactRepeating() instead of setRepeating(). setRepeating only takes set intervals with the shortest being INTERVAL_FIFTEEN_MINUTES. setInexactRepeating() is the only way to set a repeating interval as short as 1000ms, or 5000ms in your case.
Change:
manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
to
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
If you are not getting the exact 5 second delay that you need, you will need to use a Handler. Any type of alarm with a 5 second delay will not work properly because as of Android 5.x basically all repeating alarms are inexact to save battery life.
I have modified your code to use a Handler:
startAlarm();
public void startAlarm() {
final Handler h = new Handler();
final int delay = 5000; //milliseconds
h.postDelayed(new Runnable(){
public void run(){
//do something
Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
sendBroadcast(alarmIntent);
h.postDelayed(this, delay);
}
}, delay);
}
That alarm method will work with your current BroadcastReceiver and do an actual 5 second delay.

Alarm Manager goes off as i click the Button

I have the code set on a button which sets the alarm manager to send broadcast and activate the WiFi on the device. I have set the delay for 1 min but code but the alarm goes off as soon as I click the button
Here's the code on button:
public void start(View view){
AlarmManager alarm = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent1 = new Intent(this,MyReceiver.class);
PendingIntent TurnWiFi = PendingIntent.getBroadcast(getApplicationContext(), 0, intent1, 0);
long milli = 60000;
alarm.set(AlarmManager.RTC,milli,TurnWiFi);
}
The code in Receiver:
public class MyReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Log.i("BroadcastReceiver","------------>In on receive method<-------------");
WifiManager wifi_man = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifi_man.setWifiEnabled(true);
}
in alarm.set(AlarmManager.RTC,milli,TurnWiFi); milli is already passed
use Calendar for less complexity.
this should solve your problem:
alarm.set(AlarmManager.RTC,System.currentTimeMillis() + milli,TurnWiFi);
UPDATE:
Explanation:
If the stated trigger time is in the past, the alarm will be triggered immediately
trigger for AlarmManager.RTC (Real Time Clock) type is time of day represented by milliseconds. and 60000 millis is literally in the past.
according to documents, System.currentTimeMillis() + 60000 goes off in next 60secs
System.currentTimeMillis()
Returns the current time in milliseconds since January 1, 1970 00:00:00.0 UTC.

setting alarm on boot time at a specific time every day

I have started alarm of 9:00 AM in android on Boot Completed. But fires alarm every minute after it has completed boot.
My Requirement is it should set Alarm after boot but only fires alarm at 9:00 AM.
Here is my code:
public class AlarmUtil {
private PendingIntent alarmIntent;
public static void setAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 00);
calendar.set(Calendar.SECOND, 00);
calendar.set(Calendar.AM_PM, Calendar.AM);
//calendar.setTimeInMillis(calendar.getTimeInMillis());
calendar.add(Calendar.SECOND, 1);
Intent intent = new Intent(context, Services.class);
PendingIntent pintent = PendingIntent.getService(context, 123456789,
intent, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);
}
}
public class AlarmBroadcastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Toast.makeText(context, "Booted!", Toast.LENGTH_SHORT).show();
AlarmUtil.setAlarm(context);
}
}
}
services (My service Class)
public class Services extends IntentService {
public Services(String name) {
super("services");
// TODO Auto-generated constructor stub
}
public Services() {
super("services");
// TODO Auto-generated constructor stub
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyApp.counter += 1;
Toast.makeText(getApplicationContext(),
"Service started: " + MyApp.counter, Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
Toast.makeText(getApplicationContext(), "handling intent",
Toast.LENGTH_LONG).show();
}
}
where i am lacking. Please help me. Thanks in advance.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1 * 60 * 1000, pintent);
By calling setRepeating(), you are instructing it to fire the intent on every minute. You probably meant to use set() or setExact() instead.
Additionally, you're setting the alarm for 9:00 on the current date. I'm not exactly sure what your objective is but if you want an alarm for the "next 9:00" (i.e. as an alarm clock) you should probably add a day if the current time is greater than 9:00. From the documentation:
If the stated trigger time is in the past, the alarm will be triggered
immediately.
EDIT: If what you need is to fire this alarm every day at 9:00, then setRepeating() is correct, but the time in milliseconds should be AlarmManager.INTERVAL_DAY. Be mindful of the note about past alarms, though. If you boot your phone, say, at 10:00 AM, and you use your current code, you will get an immediate alarm in addition to the future ones.
And, as #DerGolem pointed out, if you target API level 19 then these alarms will be inexact (and there is no setRepeatingExact()). If you need exact alarms, then you will have to schedule one with setExact(), then the next one when that one fires, and so on.
Hi I have used following code and able to generate alarm at 9 Am each day
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmService.class);
PendingIntent pintent = PendingIntent.getService(this, 123456789,
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, 9);
calendar.set(Calendar.MINUTE, 00);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), 1000 * 60 * 1 * 60 * 24, pintent);
you need to replace "1 * 60 * 1000" with AlarmManager.INTERVAL_DAY to set it daily

My Recurring Task doesn't get called

I am trying to use AlarmManager to accomplish a recurring task. I am using setInexactRepeating() and have set the interval to every 15 minutes (just for testing purposes) however, it doesn't seem to be working. Any ideas?
Here's my code:
AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.w("CacheCrusader", "Recurring Job: Clearing Cache");
}
}
Setter
private void setRecurringAlarm(Context context) {
Calendar updateTime = Calendar.getInstance();
updateTime.set(Calendar.HOUR_OF_DAY, 20);
updateTime.set(Calendar.MINUTE, 15);
Intent downloader = new Intent(context, AlarmReceiver.class);
PendingIntent recurringDownload = PendingIntent.getBroadcast(context,
0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarms = (AlarmManager) getSystemService(
Context.ALARM_SERVICE);
alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
updateTime.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES, recurringDownload);
}
Code that Sets the Setter
Context context = getApplicationContext();
setRecurringAlarm(context);
Android Manifest Declaration
<receiver android:name=".receiver.AlarmReceiver"></receiver>
No errors are generated in the logcat... the alarm just never fires.
Well, it's inexact so... If you set it the interval to 15 mins, you have to wait for at least half an hour to be sure it has/has not fired. After the starting time you have set (20:15). Try it out with something like 1 min interval for testing. And, if you need a more reliable schedule, use setRepeating(), or possibly set() where each alarm invocation registers the next one.

Categories

Resources