Just tried this on my instance and:
Device device = request.adaptTo(Device.class);
returns null
, while:
DeviceGroup deviceGroup = request.adaptTo(DeviceGroup.class);
on the other hand, gets me a reference to a valid DeviceGroup
object.
If you need a device and not a group, try using DeviceMapper
. It appears that the DeviceMapper
is indeed available as a service implemented by com.day.cq.wcm.mobile.core.impl.devicemapper.DeviceMapperImpl
Therefore, in you JSP, you can simply write:
<%@ page import="com.day.cq.wcm.mobile.api.device.DeviceMapper" %>
...
<%
DeviceMapper deviceMapper = sling.getService(DeviceMapper.class);
Device device = deviceMapper.getDeviceInstance(slingRequest);
%>
And that should give you the right object provided that all of the relevant configurations are right.
However, if possible, you should try to avoid placing such logic in your JSP.
This kind of code should be encapsulated in an adapter factory or preferably a Sling Model. That way you'll be able to get rid of all of your code from the presentation layer and just read simple properties in the JSP.
You may also want to take a look at the com.day.cq.wcm.mobile.core.MobileUtil.class
that might just fit your particular use case.
I'd also like to point out that writing back-end code to target a specific device (as opposed to a group) seems a bit strange. Before introducing a bunch of classes to detect the device, think if the same result can be achieved using appropriate styling, a mobile site version, Target (if the purpose is to serve different content to users with different devices). Or maybe you should just go for AEM Apps