I'm trying to make Android fire a Alarm at a certain time the user specifies to check if the user has posted to the service. However, Android won't fire the intent.
AndroidManifest.xml:
<receiver
android:name="me.kennydude.dailybooth.NoBoothNotify.AlarmReciever" />
<service
android:name="me.kennydude.dailybooth.NoBoothNotify.AlarmService">
</service>
NoBoothNotify.java function that sets the alarm:
public static void settingsChanged(){
Context cntxt = DailyboothApplication.getInstance();
String value = DailyboothShared.getPersonalSetting("noBoothNotify", "no");
AlarmManager alm = (AlarmManager) cntxt.getSystemService(Context.ALARM_SERVICE);
Intent piI = new Intent(cntxt, AlarmReciever.class);
if(Build.VERSION.SDK_INT >= 5){
SharedPreferences prefs = DailyboothShared.getPrefs();
piI.putExtra("account", prefs.getString("current_account", null));
}
PendingIntent pi = PendingIntent.getBroadcast(cntxt, 348347873, piI, PendingIntent.FLAG_UPDATE_CURRENT);
if(value.equals("no")){
alm.cancel(pi);
} else{
String[] values = value.split(":");
Calendar cal = Calendar.getInstance();
Log.d("s", value);
// cal.setTimeInMillis(System.currentTimeMillis());
cal.clear(Calendar.HOUR_OF_DAY);
cal.clear(Calendar.SECOND);
cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(values[0]));
cal.set(Calendar.MINUTE, Integer.parseInt(values[1]));
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
Log.d("s", "setting for " + cal.getTimeInMillis());
Log.d("s", "HRD: " + cal.getTime().toGMTString());
alm.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
/*AlarmManager.INTERVAL_DAY,*/ pi);
}
}
As you can see I'm trying to just get it working one (hence the commented out part), however it doesn't work still.
Can anyone help?
Thanks,
Joe
I seem to have fixed this. For some reason Android doesn't like to fire Alarms if the receiver is a subclass.
To fix and keep origination, I moved it all to a new namespace and it worked.
Joe
Related
I am new to android ,here I am developing an alarm app for my working knowledge .
I have completed the following :
creating alarms and storing it into sqlite database.
Fetching all the alarms which has the status as active .
I have tried many stackoverflow post and their solutions and other blog posts which related to my doubt but I can't get a solution for my problem .
What is my problem is I am receiving number of alarm timings from sqlite database which I have set it before and I want to set all the alarms on the stored time .
Here I don't know how to set it .
Can anyone help me to set the multiple alarms .
I am really looking for someone's help to learn and experience these things please help me .
Thanks.
You need Alarm Manager and Pending Intent more.
for (int i = 0; i < ActivemyAlarms.size(); i++) {
int mHour = 0,mMin=0;
String amPm = null;
int mAlarmId = ActivemyAlarms.get(i).getALARM_ID(); //each alarm has an unique Id ,for differentiate one from another
String mAlarmTime = ActivemyAlarms.get(i).getALARM_TIME(); // alarm time (11:12:AM)
if (!(mAlarmTime == null)) {
String mtime = mAlarmTime; // alarm time format is 12hr format (ex : 11:12:AM)
String[] time = mtime.split(":");
mHour = Integer.parseInt(time[0].trim()); // get 11 hour
mMin = Integer.parseInt(time[1].trim()); // get 12 min
amPm = ((time[2].trim()));
}
Calendar calendar = Calendar.getInstance();
calendar.set(calendar.HOUR_OF_DAY, amPm!=null && amPm.equalsIgnoreCase("pm")?(mHour+12):mHour);
calendar.set(calendar.MINUTE, mMin);
calendar.set(calendar.SECOND, 0);
calendar.set(calendar.MILLISECOND, 0);
Intent intent = new Intent(this,AlarmReceiver.class); //calling my Alarm service class which plays a music on the specific time
final int _id = (int) System.currentTimeMillis(); // get calendar instance
//Use Alarm manager and Pending Intent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), alarmIntent);
}
And to cancel any Alarm call alarmManager.cancel(PendingIntent) like;
Intent intent = new Intent(this,AlarmReceiver.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, mAlarmId, intent, 0);
alarmManager.cancel(alarmIntent);
I have a broadcast receiver class which I call at the beginning of a new day.
Here is the broadcast receiver onReceive method.
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent(NEW_DAY_FROM_RECEIVER));
Log.d(TAG, "Old day passed, new day in!");
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d");
Date yesterdaysDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000L);
String yesterdaysDateString = dateFormat.format(yesterdaysDate);
// Saving the value
DailyPointsItem yesterdayPointsItem = new DailyPointsItem(yesterdaysDateString, String.valueOf(pointsForToday), notEatenItemsArrayList, DailyPointsItem.DAILY_FOOD_POINT);
Log.d(TAG,"Points: " + yesterdayPointsItem.getTitle() + " : " + yesterdayPointsItem.getDescription());
addDailyPointsItem(context, yesterdayPointsItem);
}
public static void addDailyPointsItem(Context context, DailyPointsItem yesterdayPointsItem) {
ArrayList<DailyPointsItem> dailyPointsDataList = SharedPreferencesManager.getDailyPointsItemsArrayList(context);
dailyPointsDataList.add(0, yesterdayPointsItem);
if(dailyPointsDataList.size()==8){
dailyPointsDataList.remove(7);
}
final SharedPreferences.Editor editor = getSharedPreferences(context).edit();
Gson gson = new Gson();
String jsonDailyPointsArray = gson.toJson(dailyPointsDataList);
editor.putString(JSON_STRING_POINTS_ARRAY, jsonDailyPointsArray);
editor.apply();
}
Here I store the string yesterdaysDateString (which is the string of the previous day that just passed), and display this data some place else.
This broadcast receiver I call at the begining of each day using an AlarmManager, called in my Main Activity when the app starts, like this:
Intent intent = new Intent(this, NewDayReceiver.class);
AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, intent, 0);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.DATE, 1);
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
if (!calendar.before(Calendar.getInstance())) {
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 24 * 60 * 60 * 1000, pendingIntent); //Repeat every 24 hours
Log.d(TAG, "New day alarm set for:" + calendar.getTime() + " and will repeat every day");
}
Now this works fine, and each day that comes in the date is stored in the string. However the date is only correctly saved if the app is opened each day. If the app isn't opened each day, the AlarmManager works and the broadcast receiver is called, however the date that is saved is the date of the last day the app was open. If for example the app was opened Sun, Mar 25, and not opened for 3 days. then the three dates that are stored are Sun, Mar 25. Why is the Broadcast receiver not saving the current date.
EDITED: It works when the phone is used, but if the phone isn't used and left idle, it doesn't save the correct date. Why would this be so?
Hello friends that I developed an application Creating courses. I want to give notice when the time course.
So if you have classes Monday at 8 o'clock. 8 hours per week of class time came. I want to create a notification. I'm doing this with the alarmmanager and notification. I can give you one-time alarms. But somehow I could not repeat. Codes as follows. I will not try it because it is part of recevice.
private void alarmla() {
SQLiteDatabase db=activity.openOrCreateDatabase("SINIFD",activity.MODE_PRIVATE,null);
Cursor c = db.rawQuery("select * from ders", null);
if(c.getCount()>0){
c.moveToFirst();
do {
AlarmManager alarmManager = (AlarmManager) activity.getSystemService(Context.ALARM_SERVICE);
Toast.makeText(activity, c.getString(3).split(":")[0] + " " + c.getString(3).split(":")[1], Toast.LENGTH_LONG).show();
Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
notificationIntent.addCategory("android.intent.category.DEFAULT");
notificationIntent.putExtra("message", c.getString(1) + " dersi zamanı geldi. Kazanımlara ulaşmak için tıklayınız. İyi dersler.");
notificationIntent.putExtra("gizli", c.getString(6));
PendingIntent broadcast = PendingIntent.getBroadcast(activity, c.getInt(0), notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Calendar timeOff = Calendar.getInstance();
int days = Calendar.FRIDAY + (7 - timeOff.get(Calendar.DAY_OF_WEEK)); // how many days until Sunday
timeOff.add(Calendar.DATE, days);
timeOff.set(Calendar.HOUR, Integer.parseInt(c.getString(3).split(":")[0])); //buraya 22 geliyor databaseden
timeOff.set(Calendar.MINUTE,Integer.parseInt(c.getString(3).split(":")[1])); //buraya 10 geliyor mesala
timeOff.set(Calendar.SECOND, 0);
timeOff.set(Calendar.MILLISECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeOff.getTimeInMillis(),AlarmManager.INTERVAL_DAY * 7, broadcast);
} while (c.moveToNext());
c.close();
}
db.close();
Toast.makeText(activity,"Vay be ayar ",Toast.LENGTH_LONG).show();
}
When there is no problem with the database of the adjustment.
Do not forget relaunch alarm manager after rebooting your mobile device!
Use broadcast receiver to catch this action
More about reboot : Trying to start a service on boot on Android
I am using this code to launch an Alarm.
The alarm is set in an Activity that the user can launch.
//Setting alarm to fire off NEW_GAME intent every 24 hours.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
int currentDate = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, currentDate+1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent("NEW_ITEM");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
I was told i need to supply a uniqu id so that the alarm doesnt over writte each other where getBroadcast() is.
The problem is how do I do this when the user can open the Activity as many times as they want?
Also if I supply a unique ID each time this means it could possibly set 5 of the same ALARMS because of the unique id's.
How or what is the best way to get around this?
you could always just use the unix timestamp of your target time as the unique id. that way, alarms for the exact time WILL override each other, while all other alarms will stay seperate
[EDIT:] Here is some example code:
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent(String.valueOf(calendar.getTimeInMillis()));
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
I am using this code to set a Alarm everyday for 8 oclock the next day.
I am setting this alarm in an activity that can be opened based upon the user.
//Setting alarm to fire off NEW_GAME intent every 24 hours.
String alarm = Context.ALARM_SERVICE;
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 8);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND,0);
calendar.set(Calendar.MILLISECOND, 0);
Log.i("Test", "Current time: " + System.currentTimeMillis() );
Log.i("Test", "Calendar time: " + calendar.getTimeInMillis() );
int currentDate = calendar.get(Calendar.DATE);
calendar.set(Calendar.DATE, currentDate+1);
Log.i("Test", "Calendar time with a day added: " + calendar.getTimeInMillis() );
AlarmManager am = (AlarmManager)getActivity().getSystemService(alarm);
Intent intent = new Intent("NEW_ITEM");
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() , AlarmManager.INTERVAL_DAY, sender);
My only question is..Lets say at 10:00 o clock today am. i open the activity that alarm is set for tomorrow..Lets say i open the activity again at 12:00 am mid-night, will the alarm set earlier that day be overr written by the current alarm being set?
If you use the same request number (second parameter) while creating the PendingIntent object
PendingIntent sender = PendingIntent.getBroadcast(getActivity(), 0, intent, 0);
then it will overwrite the current PendingIntent and hence will replace the current Alarm.
It will also depend on what you pass as the last parameter to it. Possible values given in the constants section here.