Android detects if at night

Is there a better way than this?

Boolean isNight; Calendar cal = Calendar.getInstance(); int hour = cal.get(Calendar.HOUR_OF_DAY); if(hour < 6 || hour > 18){ isNight = true; } else { isNight = false; } 

It just checks if the time is between 7:00 and 5:00. Is there any other way to do this?

+7
source share
3 answers

Not a big difference, but you can complete the task:

 isNight = hour < 6 || hour > 18; 
+5
source

If you are using UiModeManager to turn on CarMode and NIGHT, set to AUTO. You can get a link to the current topic used when declaring an attribute to search at runtime.

attrs.xml

 <resources> <!-- Theme name reference --> <attr name="metaThemeName" format="string"/> </resources> 

night values /themes.xml

 <?xml version="1.0" encoding="utf-8"?> <resources xmlns:tools="http://schemas.android.com/tools"> <!-- Application theme. --> <style name="AppTheme" parent="Theme.AppCompat"> <item name="metaThemeName">night</item> </style> </resources> 

java.class

 ... TypedValue outValue = new TypedValue(); getTheme().resolveAttribute(R.attr.metaThemeName, outValue, true); boolean isNight="night".equals(outValue.string); ... 
+2
source

values \ values.xml

 <?xml version="1.0" encoding="utf-8"?> <resources> <bool name="isNightMode">false</bool> </resources> 

values ​​night \ values.xml

 <?xml version="1.0" encoding="utf-8"?> <resources> <bool name="isNightMode">true</bool> </resources> 

And now, check it out in your class class.java

 public boolean isNightMode(){ return getResources().getBoolean(R.bool.isNightMode); } 
0
source

All Articles