EDIT: Since I posted the question I've tested the app on numerous devices and also on emulator and apparently the problem wasn't with the app but with the phone I was testing it at the beginning. But now I am curious why on some phones AlarmManager
or WakefulBroadcaastReceiver
(I don't really know which one is it) doesn't work when app is in the background and screen is locked. Can I somehow fix it via code or in device's options?
I will also add that the phone that I was testing it on and wasn't working was Huwaei P8 Lite with Android 5.0.1
Original question:
I am using AlarmManager
in my app to display notifications in some time intervals. It works fine when app is open or when the app is in background ( for example after I press home button). It also works when I lock phone screen while app is active. But when I lock the phone when my app is in the background my BroadcastReceiver
isn't being called by AlarmManager
. Why is that? The problem is even in AlarmManager or maybe rather in my receiver?
Also I have bonus question: Is it possible for my alarm in AlarmManager to work after app is killed?
Here is my code:
public class NotificationService extends IntentService {
public NotificationService(String name) {
super(name);
}
public NotificationService() {
super("NotificationService");
}
@Override
protected void onHandleIntent(Intent intent) {
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Notification notification = new Notification.Builder(this).setContentTitle("TEXT")
.setContentText("TEXT")
.setLights(Color.GREEN,1000,500)
.setSmallIcon(R.drawable.ic_event_white_24dp).getNotification();
notificationManager.notify(0,notification);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Intent i = new Intent(this,AlarmReceiver.class);
PendingIntent pi = PendingIntent.getBroadcast(this,0,i,0);
long nextAlarm = System.currentTimeInMillis()+1000*60;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
AlarmManager.AlarmClockInfo alarmClockInfo = new AlarmManager.AlarmClockInfo(nextAlarm, pi);
alarmManager.setAlarmClock(alarmClockInfo, pi);
}else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(android.app.AlarmManager.RTC_WAKEUP, nextAlarm, pi);
}else {
alarmManager.set(android.app.AlarmManager.RTC_WAKEUP, nextAlarm, pi);
}
AlarmReceiver.completeWakefulIntent(intent);
}
Receiver:
public class AlarmReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.e("test","onReceive started");
Intent i = new Intent(context,NotificationService.class);
startWakefulService(context,i);
}
}
When the screen is locked and app is in the background receiver is never started since i cant see the line : Log.e("test","onReceive started");
executed
I do have WAKE_LOCK permission in manifest