AlarmManager executed even if the time is wrong - java

I am using the following code to execute the Alarm at 10:30 AM and then keep executing every 8seconds, but the problem is, this code execute the Alarm manager even when the time is not 10:30.
I have tried everything but the code keep executing the Alarm regardless of what time is set,
public class MainActivity extends Activity {
private PendingIntent pendingIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* Retrieve a PendingIntent that will perform a broadcast */
Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
startAt10();
}
public void startAt10() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
/* Set the alarm to start at 10:30 AM */
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 10);
calendar.set(Calendar.MINUTE, 30);
/* Repeating on every 8 seconds interval */
manager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 8, pendingIntent);
}
}
and this is my AlarmReceiver class,
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// For our recurring task, we'll just display a message
Toast.makeText(context, "Welcome Back ! ", Toast.LENGTH_SHORT).show();
}
I have also added this in my AndroidManifest.xml,
<receiver android:name="com.example.test2.AlarmReceiver" android:enabled="true" >
</receiver>
How to make it to only execute at 10:30AM ?

Your code is correct. The alarm will start at 10:30 am and repeats at every 8 seconds. But once check the time in the device or emulator in which your app is running. If the time is already past then the alarm starts executing immediately.
If the time is not completed then once uninstall the application and run again it may work.

Related

AlarmManager is not showing toast message at specified time

I want my app to run a specific task at exactly 9 pm every day. I have read multiple examples of it being implemented in Android apps, and I have tried almost every one of them, but nothing seems to work. To test the code out, I try to show a toast message at a certain time, but no toast message comes up, even minutes later after the set time because I read on some sites that the Alarm time may not be exact. Please help me figure out what the problem with my code is.
MainActivity.java:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Intent intent = new Intent(this, MyBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 21);
calendar.set(Calendar.MINUTE, 00);
if (alarmManager != null) {
alarmManager.setExact(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
}
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(MainActivity.this, "Alarm...", Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
Any help is highly appreciated. I have been stuck with this issue for hours. Thank you.

How do I create multiple scheduled notifications each on specific days of the week and time

I need to create multiple notifications that each have a certain day of the week to display at a certain time. E.g. Every Monday at 8pm and when the notification is clicked it should go to a activity in my application. I also have a settings activity where the user can choose which notifications they want to show or not.
I have looked at loads of examples and even android docs but haven't figured out a way to get this working.
Thanks in advance.
Exact times might be quite difficult due the the different restrictions on background processing by the system. But a satisfactory solution might be to use alarm manager.
https://developer.android.com/training/scheduling/alarms#examples-of-real-time-clock-alarms
Taken from the above docs
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,
// 24 hours.
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60 * 60 * 24, alarmIntent);
You'll have to create and register the AlarmReceiver
public class AlarmReceiver extends BroadcastReceiver
{
public AlarmReceiver (){}
public void onReceive(Context context, Intent intent)
{
doSomething();
}
}
Register receiver somewhere in activity
private AlarmReceiver receiver = new AlarmReceiver();
this.registerReceiver(this.receiver, new IntentFilter());

Alarm Manager not starting after 60 seconds

I'm trying to set my alarm manager working, just simple schedule, firing toast every minute, but it's not working, what's wrong with the code?
Main Activity :
public void klik(View view) {
startalarm();
}
public void startalarm(){
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent;
PendingIntent pendingIntent;
intent = new Intent(this, AlarmToastReciever.class);
pendingIntent = PendingIntent.getBroadcast(this,0,intent,0);
manager.setRepeating(AlarmManager.RTC_WAKEUP, SystemClock.elapsedRealtime()+3000,+60000,pendingIntent);
}
}
AlarmToastReciever class :
public class AlarmToastReciever extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent){
Toast.makeText(context,"GOWNO", Toast.LENGTH_SHORT).show();
}
}
As stated in documentation
As of Android 4.4 (API Level 19), all repeating alarms are inexact. Note that while setInexactRepeating() is an improvement over setRepeating(), it can still overwhelm a server if every instance of an app hits the server around the same time. Therefore, for network requests, add some randomness to your alarms, as discussed above.
You can use "setInexactRepeating()" or set an exact one time alarm then set next alarm in On Receive method
Also make sure you added your receiver to the manifest file, between application tag, like
<receiver android:name=".AlarmToastReciever"
android:enabled="true">
<intent-filter>
</intent-filter>
</receiver>
Use this code to initialize alarm manager.
public void setupAlarm() {
final Calendar calNow = Calendar.getInstance();
final Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, calNow.get(Calendar.HOUR_OF_DAY));
calSet.set(Calendar.MINUTE, calNow.get(Calendar.MINUTE) + 1);
calSet.set(Calendar.SECOND, calNow.get(Calendar.SECOND));
final Intent intent = new Intent(this, UploadStarterReceiver.class);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1,
intent, 0);
final AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(),
60 * 1000, pendingIntent);
}

Setting an alarm from inside another alarm using AlarmManager class not getting fired correctly

The below code is from my MainActivity onCreate() method where I set an alarm to run a service ScheduleAlarm immediately and only once. sPrefs is the SharedPreference object that takes care of setting this alarm only once. The service ScheduleAlarm is an IntentService which is getting fired perfectly.
if(sPrefs.getBoolean("SettingAlarmForFirstTime",true)) {
//Creating alarm for showing notifications.
Calendar calendar = Calendar.getInstance();
//calendar.setTimeInMillis(System.currentTimeMillis());
//calendar.set(Calendar.HOUR_OF_DAY, 8);
Intent intent = new Intent(MainActivity.this, ScheduleAlarms.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);//Use AlarmManager.INTERVAL_DAY instead of int number here.
editor.putBoolean("SettingAlarmForFirstTime", false);
editor.commit();
}
Now this is my ScheduleAlarms service class. When this service is started onHandleIntent() method is called from where I am calling setWeeklyAlarms() method. Now my problem is from inside this method I want to set 7 alarms for a complete week based on timings that I will obtain from an API server call. Right now I am unable to even execute a single alarm perfectly. The alarm that i am setting is set to start after 3 secs delay which will call another service named NotificationService but the alarms gets fired immediately instead of waiting for 3 secs. Please analyze and tell me why this is happening.
public class ScheduleAlarms extends IntentService {
private boolean notificationsEnabled = true;
private String notificationTimings = "";
public ScheduleAlarms() {
super("ScheduleAlarms");
}
#Override
protected void onHandleIntent(Intent intent) {
setWeeklyAlarm();
}
private void setWeeklyAlarm() {
Intent i = new Intent(ScheduleAlarms.this, NotificationService.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getService(ScheduleAlarms.this, 10001, i, 0);
AlarmManager alarmManager = (AlarmManager) ScheduleAlarms.this.getSystemService(Context.ALARM_SERVICE);
/* Setting this alarmManager to fire up the alarm after 3 mins delay, but this alarm is getting fired immediately*/
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 3*60*1000, pendingIntent);
}
}
Change the following line:
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, 3*60*1000, pendingIntent);
to:
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis() + 3 * 60 * 1000, 3 * 60 * 1000, pendingIntent);
The alarm is fired up immediately, because
AlarmManager.ELAPSED_REALTIME_WAKEUP + 0, ...
So, the first time, it is fired up after 0 seconds. To change this, you need to add some time here.
AlarmManager.ELAPSED_REALTIME_WAKEUP + time
And, also it should be repeating, so you need to use setRepeating.
Note : 3 * 60 * 1000 == 3 minutes, not 3 seconds

AlarmManager responding at wrong time

Sorry if answered before, but i looked everywhere but didn't get the proper solution
I am using AlarmManager to automatically fire a notification at 9am everyday, but when i try to run it on emulator it executes immediately, and every half hour (31-32min to be precise) after that instead of only once at 9am everyday.
Any ideas why? help appreciated.
code is as below:
public class Home extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bsheet);
notificationAlert(savedInstanceState);
}
private void notificationAlert(Bundle savedInstanceState) {
AlarmManager manager;
PendingIntent pendingIntent;
Intent intent=new Intent(Home.this, Notify.class);
manager=(AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent=PendingIntent.getService(Home.this,
0, intent, 0);
GregorianCalendar gcal = new GregorianCalendar();
gcal.set(Calendar.HOUR_OF_DAY, 9);
gcal.set(Calendar.MINUTE, 0);
gcal.set(Calendar.SECOND, 0);
gcal.set(Calendar.MILLISECOND, 0);
long initTime = gcal.getTimeInMillis();
manager.setRepeating(AlarmManager.RTC_WAKEUP, initTime,
24*60*60*1000, pendingIntent);
}
}
cheers,
EDIT: my intention is that, once the app is installed, it fires this alarm at 9am. i have put the alarm in the onCreate, so im not sure if the alarm is only being created everytime i start the app and something weird is happening when i hide the app... again insight would be appreciated!
manager.setRepeating(AlarmManager.RTC_WAKEUP, initTime, 24*60*60*1000, pendingIntent);
Alarm manager will fire immidiatly if initTime < System.currentTimeMillis()
from docs:
If the time occurs in the past, the alarm will be triggered immediately, with an alarm count depending on how far in the past the trigger time is relative to the repeat interval.
According to the code you've provided, gcal.getTimeInMillis() will return millisecods corresponding to Today 9.00. So if you'll try to run your code after this time, initTime will be less then current system time which triggers immidiate run of AlarmManager.
To fix this, for example, you can add one day to your calendar before passing its gcal.getTimeInMillis() if it is already in past so it will point to Tomorrow 9.00 to let it run tomorrows morning
Update1
Tried code like this and it worked as expected for me - fired service every 10 seconds:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initManager();
}
private void initManager() {
AlarmManager manager;
PendingIntent pendingIntent;
Intent intent = new Intent(this, NotifyService.class);
manager=(AlarmManager)getSystemService(ALARM_SERVICE);
pendingIntent=PendingIntent.getService(this, 0, intent, 0);
long initTime = System.currentTimeMillis() + 5000;
manager.setRepeating(AlarmManager.RTC_WAKEUP, initTime,
10*1000, pendingIntent);
}
However you can use another option: there is AlarmManager.set() method
You can fire it like this
long runTime = /* your calendar time + 24 hours in millis*/
manager.set(AlarmManager.RTC_WAKEUP, runTime, pendingIntent);
so it will fire your service at runTime. And then in the service invoke the same method with recalculated runTime for another day so it could look something like that:
public MainActivity extends Activity{
protected onCreate(Bundle bundle){
....
initManager();
}
private initManager(){
...
long runTime = /* time of your first alarm/notification/whatever you develope */
Intent intent = new Intent(this, NotifyService.class);
pendingIntent=PendingIntent.getService(this, 0, intent, 0);
manager.set(AlarmManager.RTC_WAKEUP, runTime, pendingIntent);
}
}
And the service:
public NotifyService extends Service{
...
public int onStartCommand(...){
...
/* do stuff */
Intent intent = new Intent(getApplicationContext(), NotifyService.class);
pendingIntent=PendingIntent.getService(this, 0, intent, 0);
long runTime = /* recalculate it according to the next time of firing this service*/
manager.set(AlarmManager.RTC_WAKEUP, runTime, pendingIntent);
}
}
So your service will register an intent in AlarmManager itself everytime the service fires.
try this :
Calendar currentTime = Calendar.getInstance();
Calendar alarmTime = Calendar.getInstance();
currentTime.set(Calendar.HOUR_OF_DAY, 9;
currentTime.set(Calendar.MINUTE, 0);
currentTime.set(Calendar.SECOND, 0);
currentTime.set(Calendar.MILLISECOND, 0);
if (alarmTime.compareTo(currentTime) <= 0) {
// check for time
alarmTime.add(Calendar.DATE, 1);
}
Intent intent = new Intent(getBaseContext(), Receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getBaseContext(), 1, intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, alarmTime.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);

Categories

Resources