Alarm Manager goes off as i click the Button - android

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.

Related

Alarm Manager is sometimes very long to run the intent

I got a problem with the AlarmManager. When the alarm is set, if the alarm's hour has already passed the intent is started which is great. But sometimes there is a very long time (from 30 secondes to 3 minutes) before the intent is started. If anyone knows why, I'm curious to understand.
Here is my code :
public static void setAlarm()
{
Intent intent = new Intent(Application.Context, typeof(AlarmReceiver));
intent.SetAction("ExchangeGo");
PendingIntent pendingIntent = PendingIntent.GetBroadcast(Application.Context, 0, intent, PendingIntentFlags.CancelCurrent);
Calendar dayCalendar = Calendar.GetInstance(Java.Util.TimeZone.Default);
dayCalendar.Set(CalendarField.HourOfDay, 8);
dayCalendar.Set(CalendarField.Minute, 30);
dayCalendar.Set(CalendarField.Second, 0);
dayCalendar.Set(CalendarField.Millisecond, 0);
AlarmManager alarm = Application.Context.GetSystemService(Context.AlarmService).JavaCast<AlarmManager>();
alarm.Cancel(pendingIntent);
alarm.SetRepeating(AlarmType.RtcWakeup, dayCalendar.TimeInMillis, AlarmManager.IntervalDay, pendingIntent);
}
And here the intent :
[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
private String SOMEACTION = "ExchangeGo";
public override void OnReceive(Context context, Intent intent)
{
String action = intent.Action;
if (SOMEACTION.Equals(action))
{
Intent intentService = new Intent(context, typeof(ExchangeService2));
context.StartService(intentService);
}
}
}
There is no problem with manifest cause it works, just a bit too long sometimes. And the problem is not from my second intent because I put a breakPoint just before and the waiting time is before the break point.
Anyone ?
Thanks for reading me.
As setRepeating() doesn't guarantee that it will happen at precise time.
That's why you are getting delay of 30 secondes to 3 minutes.
Replace setRepeating() with setExact() refer documentation from Here
manager.setExact(AlarmManager.RTC, startTime.getTimeInMillis(), operation);
To repeat this what you can do is, to schedule this alarm again after executing your current event. So when your 1st intent gets executed schedule alarm for 2nd event using setExact() only. This will guarantee the time accuracy you are expecting

Alarm manager triggered immediately

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);

Modifying Alarms Which Trigger Services Based on Screen Status

I am currently starting a service using a Broadcast Receiver which fires 60 seconds after the device boots up. This broadcast receiver triggers an alarm so that my service runs every 60 seconds. Code for this is as follows:
public class ScheduleReceiver extends BroadcastReceiver {
// Restart service every 60 seconds
private static final long REPEAT_TIME = 1000 * 60;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, i,PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 60 seconds after boot completed
cal.add(Calendar.SECOND, 60);
// Fetch every 60 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), REPEAT_TIME, pending);
}
}
The above starts the service as follows:
public class StartServiceReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service = new Intent(context, PhotoService.class);
context.startService(service);
}
}
I would like to somehow modify this so that my service runs every 60 seconds when the phone screen is on and every 20 minutes when off.
What is the best way to do this ? Can I modify the alarm dynamically when the screen is switched off/on ?
Thanks for any help,
Regards,
Fido
Okay I have found out how to do this so I thought I would put this here in case anyone else is ever curious. (More elegant solutions are always welcome):
First thing is that in my service I added the following to the OnCreate:
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScheduleReceiver();
registerReceiver(mReceiver, filter);
}
This is done so that my broadcast receiver can handle those events. Apparently you cannot register these via intent-filters in the xml.
This means that when the service is created it ensures that these additional system actions can be handled.
I then modified my broadcast receiver to be:
public class ScheduleReceiver extends BroadcastReceiver {
private static final int ALARM_ID = 909;
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
AlarmManager service = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, StartServiceReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, ALARM_ID, i,PendingIntent.FLAG_CANCEL_CURRENT);
service.cancel(pending);
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 60); //Delay startup by one minute - This is useful to prevent over utilization of resources at boot
// Start alarm. Set a long repeat time if the screen is off and a short repeat time if the screen is on
if (intent.getAction().equals(Intent.ACTION_SCREEN_ON) || intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 60000, pending);
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
service.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 600000, pending);
}
}
}
From the above I cancel any current alarms with the same pending intent and then I set a new alarm whenever the screen if switched off/on.
This seems to be working for me. As always any improvements are very welcome.

start repeating alarm from AlarmManager

I want to start a service every day from 8am to 6pm. I am using 3 alarms.
For starting alarm2 everyday at 8am.
For starting service every 1 min.
To stop alarm2.
Is it the proper way? Also I am unable to start alarm2 from alarm1.
This is code for alarm 1:
public class AlarmReceiver1 extends BroadcastReceiver {
int interval;
#Override
public void onReceive(Context context, Intent intent) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent in=new Intent(this,AlarmReceiver2);
PendingIntent startingIntent = PendingIntent.getBroadcast(context, 0,in, 0);
long duration = interval * 60 * 1000;
manager.setRepeating(AlarmManager.RTC_WAKEUP,timeOn.getTimeInMillis(), 86400000,startingIntent);
}
}
Far from enough code to tell if it has been set up properly. There is a good example here on how you should set up the AlarmManager. I'd recommend looking it through if there is something you've missed.
Also as you can see in the example you gotta reset the Alarms every time the phone is rebooted. If you don't the services will not run.

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