I'm currently developing an application which makes use of Android's AlarmManager. I'm trying to add a new alarm to the AlarmManager, but after several hours of trying various things and checking various threads on SO, I'm still at a brick wall. Are there any problems with my code?
Main Activity - saveAlarm() function
/**
* Saves the current alarm. Adds to the database if it doesn't already exist, or updates if it does.
* Also sets alert with AlarmManager.
*/
public void saveAlarm() {
// Create Database instance
DbHandler db = new DbHandler(getApplicationContext());
if(alarm.getId() == -1) {
// Saving a new alarm
db.open();
alarm.setId(db.addAlarm(alarm));
db.close();
}
else {
db.open();
db.updateAlarm(alarm);
db.close();
}
// Create the wakeup intent
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("alarm_id", alarm.getId());
// Create the Pending Intent
PendingIntent sender = PendingIntent.getBroadcast(this, AlarmPlayer.REQUEST_ALARM + alarm.getId(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Debug
Calendar now = Calendar.getInstance();
long dTime = alarm.getNextAlarmTime().getTimeInMillis() - now.getTimeInMillis();
Log.d(TAG, "Setting alarm for " + (dTime / 1000) + " seconds time");
// Add to Android Alarm Manager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarm.getNextAlarmTime().getTimeInMillis(), sender);
}
I've verified that the correct time is being passed into am.set (see the debug section above it).
AlarmReceiver.class
/**
* This class listens out for broadcasts from AlarmManager
* and launches the AlarmPlayer activity accordingly.
* @author Michael
*
*/
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context c, Intent intent) {
Log.d("RSS Alarm", "Waking up alarm");
// Launch the AlarmPlayer activity
Intent i = new Intent(c, AlarmPlayer.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
c.startActivity(i);
}
}
I also have <receiver android:process=":remote" android:name="AlarmReceiver" />
set up in AndroidManifest.xml. I have no idea what's causing this problem, but it's happening nonetheless. Any help would be greatly appreciated, many thanks in advance.
Edit 1 Changing the timezone to UTC doesn't seem to solve anything, my calendar seems to default to UTC regardless. Current code:
// Debug
Calendar now = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
long dTime = alarm.getNextAlarmTime().getTimeInMillis() - now.getTimeInMillis();
Log.d(TAG, "Setting alarm for " + (dTime / 1000) + " seconds time");
// Add to Android Alarm Manager
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
Log.d(TAG, "Timezone offset is " + TimeZone.getDefault().getRawOffset());
Log.d(TAG, "UTC time is currently " + Calendar.getInstance(TimeZone.getTimeZone("UTC")).getTimeInMillis() / 1000);
am.set(AlarmManager.RTC_WAKEUP, (alarm.getNextAlarmTime().getTimeInMillis() - TimeZone.getDefault().getRawOffset()), sender);