Android AlarmManager problem - java

I'm a new developer android application.I've problem about AlarmManager,I using
AlarmManager to set alert for my application.
I was set time to alert 2 time but my application was alert a one time
example,I'll set alarm at 15.30 and 16.30,My application will alert at 16.30 but not alert at 15.30.I've no idea to fix this problem,I hope someone please tell me to fix this problem
This my code
confirmButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
alarm();
finish();
}
});
This alarm method,I'll get date and time from button and use it to set calendar
private void alarm(){
final String day = mBtnselectDate.getText().toString();
final String time = mBtnselectTime.getText().toString();
y = day.substring(0, 4);
m = day.substring(5, 7);
d = day.substring(8);
ALARM_HOUR = time.substring(0, 2);
ALARM_MINUTE = time.substring(3);
year = Integer.parseInt(y);
month = Integer.parseInt(m);
mon = month - 1;
date = Integer.parseInt(d);
Hour = Integer.parseInt(ALARM_HOUR);
Min = Integer.parseInt(ALARM_MINUTE);
Intent AlarmIntent = new Intent(Organaizer2.this, AlarmReceiver2.class);
AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent Sender = PendingIntent.getBroadcast(Organaizer2.this, 0, AlarmIntent, 0);
Calendar alarmCalendar = Calendar.getInstance();
alarmCalendar.set(Calendar.HOUR_OF_DAY, Hour);
alarmCalendar.set(Calendar.MINUTE, Min);
alarmCalendar.set(Calendar.YEAR, year);
alarmCalendar.set(Calendar.MONTH, mon);
alarmCalendar.set(Calendar.DATE, date);
AlmMgr.set(AlarmManager.RTC_WAKEUP, alarmCalendar.getTimeInMillis(), Sender);
}
if you see problem please tell me,Thank you,Arles

Your second alarm is replacing the first alarm, because both use equivalent Intent objects. Add a call to setAction() on your AlarmIntent (BTW, recommended Java style is lowercase first letters for variables) to set a unique action string. You can also try providing a different request code (the first 0 in your call to getBroadcast()), though that parameter is not well documented and I am not sure if it will give you distinct alarms or not.

Related

How do I know the number of seconds remaining until the alarm goes off?

Scenario
i am developing an app that works kind of like subscription, i start an alarm manager for days, suppose the alarm manager has started yesterday and it should go off tomorrow, how do i know exact time remaining till alarm manager goes off?
// ALARM_MANAGER setting to expired
SharedPreferences alarmpreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor alarmEditor = alarmpreferences.edit();
alarmEditor.putString("ALARM_MANAGER", "active");
alarmEditor.apply();
AlarmManager service = (AlarmManager) getApplicationContext()
.getSystemService(getApplicationContext().ALARM_SERVICE);
Intent i = new Intent(getApplicationContext(), MyReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pending = PendingIntent.getBroadcast(getApplicationContext(), mainAlarmRequestCode, i,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// Start 20 seconds after boot completed
int secondTime = Integer.parseInt(expireTime)*60;
cal.add(Calendar.SECOND, secondTime);
//
// Fetch every 20 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), pending);
I check to see if the alarm manager is running in the 0 background with this method.
Intent i = new Intent(getApplicationContext(), MyReceiver.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
boolean alarmUp = (PendingIntent.getBroadcast(getApplicationContext(), mainAlarmRequestCode, i, PendingIntent.FLAG_NO_CREATE) != null);
if (alarmUp) {
Log.d("myTag", "Alarm is already active");
Toast.makeText(this, "alarm manager is active!", Toast.LENGTH_SHORT).show();
//alarm is active check alarm manager counter time
} else {
Toast.makeText(this, "alarm manager is not active!", Toast.LENGTH_SHORT).show(); }
The alarm manager is active, but how do I know the number of seconds remaining until the alarm goes off?
Any help would be appreciated!
You can try to store the expiration date of your AlarmManager and run a test at regular interval, to check if the current date is greater than the expiration one.

Set multiple alarms using request code

I wanna set multiple alarm using request code.
I give different values of the request codes to each alarm, but the alarmManager still executes only the last set alarm.
Here's my existing code:
public void Alarm(){
Intent intent = new Intent(MainActivity.this, BroadCast.class);
alarmID = (int)(System.currentTimeMillis() % 1000000000); //for request code
PendingIntent sender = PendingIntent.getBroadcast(
MainActivity.this, alarmID, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DATE),hours,mins,0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(),am.INTERVAL_DAY, sender);
}
try setRepeating instead of setInexactRepeating you will get repeating alarm.
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
+ (5 * 1000),5 * 1000, pendingIntent);
As of Android 5.1 (API version 22) there is a minimum period of 1 minute for repeating alarms. If you need to do work within one minute, just set the alarm directly, then set the next one from that alarm's handler, etc. If you need to do work within 5 seconds (for example), post it to a Handler instead of using the AlarmManager.
Good documetion here :
https://en.proft.me/2017/05/7/scheduling-operations-alarmmanager-android/

Android : How to use same AlarmManager in loop?

I write bellow method for alarm.
public void alarm(int time){
Intent intent = new Intent(MainActivity.this, Alarm.class);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), 0 , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
This method working perfectly. But the problem when I call the method more than one time. Like,
alarm(10);
alarm(50);
This time it only invoke alarm(10); But don't invoke alarm(50);
Anyone please help why it show this problem!
Your PendingIntent has the same properties both times you call your method. When you call PendingIntent.getBroadcast() the second time it will return the PendingIntent that was already created the first time.
If you want the alarm to trigger twice you need to do something like this:
public void alarm(int time, int requestCode){
Intent intent = new Intent(MainActivity.this, Alarm.class);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), requestCode , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
And then call it like this:
alarm(10, 0);
alarm(50, 1);
You are giving the same ID (0)
You need to use different unique id. use different pending intent id like this. you can use millisecond as id.
public void alarm(int time, int requestCode){
Intent intent = new Intent(MainActivity.this, Alarm.class);
Long timeToMilliSeconds = timeToMilliSeconds(hour, minute);
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(getApplicationContext(), timeToMilliSeconds , intent, 0);
am.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+time*1000, pi);
}
You are giving the same ID 0 (the second parameter in PendingIntent::getBroadcast) to more than onePendingIntent. This is your mistake.
Depending on the FLAG you set, the behavior may vary.
Consider either using a different ID for each PE or one of the standard flags.
Also see:
Wrong pending intent is being triggered
How does android compare pending intents
Adding flags to PendingIntent
// context variable contains your `Context`
AlarmManager mgrAlarm = (AlarmManager) context.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
for(i = 0; i < 10; ++i)
{
Intent intent = new Intent(context, OnAlarmReceiver.class);
// Loop counter `i` is used as a `requestCode`
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, i, intent, 0);
// Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000 * i,
pendingIntent);
intentArray.add(pendingIntent);
}
Call it like this
alarm(10, 0);
alarm(50, 1);
For more than one Pendingintent it needs different id so in the caller method pass
different id.

AlarmManager setRepeating()

My program is designed to create a repeating alarm that triggers a broadcastreceiver in turn making a notification. The alarm is repeated using a user-entered interval.
For example, if i want to set the alarm to run every 10 seconds, how would I do that?
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10000, calpendingintent);
Is this right? and my broadcast receiver isn't being called either for some reason.
public static void createAlarms(Context mcontext) {
cal = Calendar.getInstance();
cal.add(Calendar.HOUR, alarmintervalint);
calintent = new Intent(mcontext, AlarmBroadcastReceiver.class);
calpendingintent = PendingIntent.getBroadcast(mcontext.getApplicationContext(), 12345, calintent, 0);
am = (AlarmManager)mcontext.getSystemService(Activity.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10000, calpendingintent);
}
My broadcastreceiver class is not being called and Im not sure the "setRepeating()" method Im using is set correctly..
Please help!
use this code
AlarmManager alarmMgr;
PendingIntent pendingIntent;
public void startAlarmManager()
{
Intent dialogIntent = new Intent(getBaseContext(), AlarmBroadcastReceiver.class);
alarmMgr = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
pendingIntent = PendingIntent.getBroadcast(this, 0, dialogIntent,PendingIntent.FLAG_CANCEL_CURRENT);
alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), 10000, pendingIntent);
}
}
wheather you want to stop alarm
public void stopAlarmManager()
{
if(alarmMgr != null)
alarmMgr.cancel(pendingIntent);
}
Be Remembered dont forget to register Receiver in manifest file
<receiver android:name=".AlarmBroadcastReceiver" >
</receiver>
Use setInexactRepeating() instead of setRepeating(). When you use setInexactRepeating(), Android synchronizes repeating alarms from multiple apps and fires them at the same time.
This reduces the total number of times the system must wake the device, thus reducing drain on the battery. 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
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
long time = cal.getTimeInMillis();
Intent i = new Intent(G.context, BootCompleteReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(G.context, 0, i, 0);
G.alarmManager.set(AlarmManager.RTC_WAKEUP, time, pi);
you can use this. Hope it solves your problem
am.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + AlarmManager.INTERVAL_DAY,
AlarmManager.INTERVAL_DAY, pi);

Android notification showing some weird date in a corner

I'm not sure why when I'm showing notification there is some 1/4/70 date displaying in a top right corner? What is that? How do I get rid of it?
Code:
public static void showNotification(int id, String message, String title, String body)
{
int drawable = 0;
switch (id)
{
case NOTIFICATION_NEW_MAIL:
drawable = R.drawable.ic_notify_mail;
break;
case NOTIFICATION_AVAILABLE_TRIPS:
drawable = R.drawable.ic_notify_trip;
break;
}
NotificationManager notifyManager = (NotificationManager)MyApplication.Me.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(drawable, message, SystemClock.elapsedRealtime() + 1000);
notification.defaults |= Notification.DEFAULT_SOUND;
Intent notificationIntent= new Intent(MyApplication.Me, MailListActivity.class);
switch (id)
{
case NOTIFICATION_NEW_MAIL:
notificationIntent = new Intent(MyApplication.Me, MailListActivity.class);
break;
case NOTIFICATION_AVAILABLE_TRIPS:
notificationIntent = new Intent(MyApplication.Me, TripListActivity.class);
break;
}
PendingIntent contentIntent = PendingIntent.getActivity(MyApplication.Me, 0, notificationIntent, 0);
notification.setLatestEventInfo(MyApplication.Me, title, body, contentIntent);
notifyManager.notify(id, notification);
}
Screenshot:
That notification constructor is apparently deprecated, but anyway the last parameter in that constructor, when, should refer to in unix time what time the notification was created. SystemClock.getEllapsed time returns the amount of time since the system was booted http://developer.android.com/reference/android/os/SystemClock.html. E.g. in your case, you're saying the notication was created very recently, but in unix time you're saying you're really close to 1970. Use System.getCurrentTimeMillis() instead.
EDIT: By close to 1970 I mean Unix time is measured in milliseconds from the start of 1970. So if you say 0ms you're saying Jan 1. If you pass in 86,400,000ms (ms in a day) you're saying Jan 2, 1970. By passing in the elapsed time since boot, it'll probably report you as a day or two from Jan 1, 1970. See http://en.wikipedia.org/wiki/Unix_time
Whats that SystemClock thing? What's wrong with using System.currentTimeMillis() or System.nanoTime() ?
also, try to write a toClock() function that will convert it to a 12hr/24hr formatted time string. again, more on monday (sample code available) when i get back to the office.
I think your means is that:
Calendar canlender = Calendar.getInstance();
canlender.setTimeInMillis(System.currentTimeMillis());
canlender.add(Calendar.MILLISECOND, 1000);
long TimeInMillised = canlender.getTimeInMillis();
Notification notification = new Notification(drawable, message, TimeInMillised);
try it!

Categories