Skip to content

Instantly share code, notes, and snippets.

@PomepuyN
Last active November 5, 2018 23:07
Show Gist options
  • Save PomepuyN/cdd821eca163a3279de2 to your computer and use it in GitHub Desktop.
Save PomepuyN/cdd821eca163a3279de2 to your computer and use it in GitHub Desktop.
Allow to detect Ambient mode to switch Watch face display on Wear devices
Handler handler = new Handler(Looper.getMainLooper());
final DisplayManager displayManager = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);
displayManager.registerDisplayListener(new DisplayManager.DisplayListener() {
@Override
public void onDisplayAdded(int displayId) {
}
@Override
public void onDisplayRemoved(int displayId) {
}
@Override
public void onDisplayChanged(int displayId) {
try {
if (displayManager.getDisplay(displayId).getState() == Display.STATE_DOZING) {
updateFaceDisplay(true);
Log.d(TAG, "onDisplayChanged: dozing");
} else {
updateFaceDisplay(false);
Log.d(TAG, "onDisplayChanged: not dozing");
}
} catch (NullPointerException exception) {
}
}
}, handler);
@robUx4
Copy link

robUx4 commented Jul 10, 2014

You can set the Handler to null, unless you do this outside of the UI thread

@gatlingxyz
Copy link

So, I went to add this to my sample app and noticed something. The listener needs to be unregistered at some point, or even after the watch face is gone (switching watch faces), it will continue to call all of the methods.

@alexjlockwood
Copy link

Any particular reason why you are catching/ignoring the NullPointerException here?

try {
    ...
} catch (NullPointerException e) {
}

@LouisCAD
Copy link

LouisCAD commented Feb 8, 2016

@kentarosu onDestroy() is the perfect place to unregister 😉

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment