Android : Why do I need the WAKE_LOCK and SET_ALARM permissions?

on Saturday, April 18, 2015


I am developing an android app and testing it on my Moto G X1032. I had alarms and notifications working fine when it was running 5.1 GPE without any special permissions.


The application uses the AlarmManager, which sets an alarm in the future like so:



Intent intent = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmMgr = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmMgr.set(AlarmManager.RTC_WAKEUP, reminder.Due.getTime(), pendingIntent);


Then in the receiver, it launches a notification:



Intent intent = new Intent(context, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

Notification.Builder builder = new Notification.Builder(context);
builder.setContentTitle("My App")
.setContentText(reminder.Due.toString())
.setContentIntent(pendingIntent)
.setSmallIcon(R.drawable.ic_stat_revise)
.setLights(Color.GREEN, 750, 1400)
.setAutoCancel(true);

Notification notification = builder.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;

NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(0, notification);


It was working fine, waking the phone up (just CPU not screen) and making the usual sound, vibrating and blinking the light, then I changed a custom rom (http://forum.xda-developers.com/showthread.php?t=2780873) and that all stopped working, instead it now made the sound when I manually awoke the device.


So, after reading, I put in permissions for a wake lock and surrounded my code like so:



PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "myapp");
wakeLock.acquire();

NotificationManager notificationMgr = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationMgr.notify(0, notification);

wakeLock.release();


So now it makes the sound without a manual wake, but the light does not blink but instead is permenantly on until the notification is seen.


Also I would like to know what is the purpose of the SET_ALARM permission when I could set an alarm without it?


0 comments:

Post a Comment