I'm trying to make an alarm app and so far it works when the app is running on foreground and background. But if I close the app (swipe on running apps) the alarm doesn't go off.
This is my code
Manifest.xml
<receiver
android:name=".AlarmReceiver">
<intent-filter>
<action android:name="es.monlau.smartschool.AlarmReceiver"/>
</intent-filter>
</receiver>
MyActivity.java:
Intent intentAlarm = new Intent(this, AlarmReceiver.class);
intentAlarm.setAction("es.monlau.smartschool.AlarmReceiver");
AlarmManager alarmManager = (AlarmManager)this.getApplicationContext()
.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intentAlarm, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
AlarmReceiver.java:
@Override
public void onReceive(Context context, Intent intent){
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
if (!isScreenOn) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
sendNotification(context, title, descr, id);
}
private void sendNotification(Context context,String messageTitle, String messageBody, int id) {
Intent intent = new Intent(context, Alarma.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, id,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
boolean vibrar = settings.getBoolean("pref_notifyVibrar", true);
boolean sonido = settings.getBoolean("pref_notifySonido", true);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(context, "Alarma")
.setSmallIcon(R.drawable.logo_app_monlau)
.setContentTitle(messageTitle)
.setContentText(messageBody)
.setAutoCancel(true)
.setFullScreenIntent(pendingIntent,true)
.setLights(Color.BLUE,1,1);
if (sonido){
Uri alarmUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mRingtone = RingtoneManager.getRingtone(context, alarmUri);
mRingtone.play();
}
if (vibrar){
long[] pattern = {0, 1000, 0, 1000, 0};
notificationBuilder.setVibrate(pattern);
}
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
if (notificationManager != null) {
notificationManager.notify(id, notificationBuilder.build());
}
}
I know this is a very common problem and I've looked all the related posts.
I've triend using a Service, initiated by a another broadcast receiver with the action BOOT_COMPLETED but everything just stopped working. I don't really know what to change.