Android Implements Night Mode summary

Source: Internet
Author: User

As the app realizes more and more functions, watching the novel watching video online and so on, many people now spend more and more time on mobile devices such as mobile phone tablets. But the phone and tablet screen is not as engaging as the Kindle's ink screen, because of the self-illuminated screen features, we stare at the screen for a long time to see easy eyes ache tired, so various protection mode, Night mode in mobile app is widely used, this is indeed a thoughtful small function. So this time we explore the next several ways of realization, together learn to summarize under:


1, using the screen brightness

It is also the simplest and most effective way to reduce the brightness of the screen by using a terminal such as a mobile phone at night to reduce the intensity of light.

Please add the appropriate permissions first:

<uses-permission android:name= "Android.permission.WRITE_SETTINGS"/>
There are two ways to achieve this by setting the screen brightness:


1) Just set the brightness within the app

Typically, each activity in Android has a visual interface that sets the brightness for each activity, such as the following:

public static void setbrightness (activity activity, float Brightnessvalue)    {        Windowmanager.layoutparams LP = Activity.getwindow (). GetAttributes ();        if (Brightnessvalue > 1.0f)        {            lp.screenbrightness = 1.0f;        }        else if (brightnessvalue <= 0.0f)        {               lp.screenbrightness = 0.0f;        }        else        {            lp.screenbrightness = brightnessvalue;        }        Activity.getwindow (). SetAttributes (LP);    }

So, a program includes all the activity, we have to set its brightness alone, although it can be encapsulated as a tool to use, but the premise is there is no better way? See the other one:


2) Set the brightness of the phone system (global brightness)

Here, we are directly in the program of an activity, such as the entry activity to set the brightness of the entire phone. Because the global brightness of the phone has been set, then regardless of jump to which interface, or even quit the program, the brightness of the phone is still set brightness. Such a method is "once and for all" in relation to the first. But here we have to sort out the idea and consider several points:


After you open the app, get the original brightness value of your phone and save it (you can return to normal brightness after exiting the app)---> Assuming the phone turns on its own active brightness switch off its own active adjustment, then set the appropriate lower brightness---> apply the Set brightness value to the phone---> Finally, exit Use the saved original brightness value to restore the original brightness, and once again turn on the phone's own active brightness adjustment.


Next, paste the key code:

The first is to get the screen brightness value of the phone:

/**     * Get current system brightness     * <br> get failed return-1, get successful return normal non-negative number <br>     * @param context     * @return    * * public static int Getsystembrightness (context context)    {        int brightnessvalue =-1;        Try        {            brightnessvalue = Settings.system.                    GetInt (Context.getcontentresolver (), Settings.System.SCREEN_BRIGHTNESS);        }        catch (Exception e)        {            e.printstacktrace ();        }        return brightnessvalue;    }

Save, put directly in the sharepreference inside is good, the related code will not write.

Then check whether the phone turns on the brightness of its own active adjustment switch:

/**     * Whether to turn on your own initiative to adjust brightness     * @param contentresolver     * @return * * * Public    Static Boolean isautobrightness ( Contentresolver contentresolver)    {        Boolean autobrightness = false;        Try        {            autobrightness                    = Settings.System.getInt (contentresolver,                            Settings.System.SCREEN_ Brightness_mode)                    = = Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC;        }        catch (Exception e)        {            e.printstacktrace ();        }        return autobrightness;    }

If you open it, close it:

/**     * Stop yourself from actively adjusting brightness     * @param activity *     /public    static void closeautobrightness (activity activity)    {        Settings.System.putInt (Activity.getcontentresolver (),                Settings.System.SCREEN_BRIGHTNESS_MODE,                Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL);    }

Finally, you'll use the turn-on brightness adjustment:

public static void openautobrightness (activity activity)    {        Settings.System.putInt ( Activity.getcontentresolver (),                Settings.System.SCREEN_BRIGHTNESS_MODE,                Settings.System.SCREEN_ brightness_mode_automatic);    }

When you turn off the brightness adjustment, set the brightness, directly using the relevant code in the first method. However, because you want to apply this brightness setting to the global, you need to save the brightness value to your phone:

/**     * Save Global Brightness value setting     * @param contentresolver     * @param brightnessvalue Brightness value */public    static void Savebrightness            (contentresolver contentresolver, int brightnessvalue)    {        uri uri = android.provider.                Settings.System.getUriFor ("screen_brightness");        Android.provider.Settings.System.putInt (Contentresolver,                "screen_brightness", brightnessvalue);        Contentresolver.notifychange (URI, NULL);    }

In this way, finally the effect is OK, even if exiting the current application, the phone is still set to the lower brightness. Of course, before exiting the application should restore normal brightness and settings, so the use of the saved brightness value again set, and then save the new brightness value again to the phone can, do not forget, the phone is open before the brightness of their own active adjustment, but also to open their own active adjustment.


2, define theme yourself. (The most Frequently used method)

The definition of view, I believe that very many people are very familiar with. The definition of theme is similar to this, and is the most frequently used method to implement night mode, because it can not only achieve night mode, but also to achieve the common theme replacement function. Here is not a detail, just talk about ideas. If our application interface is white background, black text, night mode is black background, gray-white text. This night mode is different from the first adjustment brightness, because the background and content text can be arbitrarily set color and transparency, so the night mode looks more intuitive, but also more comfortable.

The definition of theme is used to define the background and text color attributes to be used in XML, for example:

<declare-styleable name= "Mythemeattrs" >        <attr name= "activity_background" format= "Color"/>        <attr name= "Text_color" format= "color"/>    </declare-styleable>

Then create your own two themes (Theme) in Style.xml, such as the default theme and night theme, set the Activity_background property to white in the default theme, the Text_color property to Black, and the night theme to black and gray, respectively. In the view layout file, give the background view used, for example, the BackgroundColor property of a relativelayout is set to "? Activity_background", and the TextColor of TextView is set to "? Text_color "just can. Of course, since this is theme, the application talent takes effect when the activity starts to initialize the view. It is therefore best to encapsulate a theme tool class yourself by calling the Settheme () method before the activity's Setcontentview () method to set the theme.


3, WindowManager implement mask mode

Here, we should be clear about a concept when you don't have to delve into the window (form). The Android design concept gives almost every component that is displayed is set to be included in a window. The activity also has its own window. By adding a layer of gray to the window to a certain degree of transparency of the view, so that it looks like the screen darkened, of course, the brightness of the phone is not changed, such an implementation, can be called "mask", similar to the camera when photographed in the lens set a layer of film or lens up, so that the effect of rendering different. But this way, there are bad places, is similar to the above said alone in each activity to set its brightness. Here every entry to an interface need to "set a layer of view" up, relative to the "once and for all" approach, appears to have no advantage. Then directly on the code:

WindowManager manager = (WindowManager) getsystemservice (context.window_service);        Windowmanager.layoutparams params = new Windowmanager.layoutparams (                WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT,                WindowManager.LayoutParams.TYPE_APPLICATION,                windowmanager.layoutparams.flag_not_touchable| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,                pixelformat.translucent);        params.gravity = Gravity.top;        Params.y = 10;//distance from the bottom is 10 pixels if top is the distance top is 10 pixels        TextView TV = new TextView (this);        Tv.setbackgroundcolor (0x55000000);        Manager.addview (Tv,params);

In the code, the touch and focus of the masked layer is forbidden by the Windowmanager.layoutparams's parameter setting. This allows you to add a layer of view without affecting the normal use of the components in the activity view.


In fact, the above three methods, in today's view, are not new technology, and on the internet I have seen a lot of relevant code, here is just put together to do a comparison and summary. The above according to three methods of implementation of the respective characteristics, in general, the first, two methods are preferable, and in the end choose the first or another method, should look at the detailed requirements, assuming that your application is simply a request to reduce brightness, do not want to change too much code, then the first one will be more suitable; If you want to have a good experience, want to look cool, and even want to add other themes, such as blue, green themes and so on, then no doubt the other is the best choice. Its extensive application of defining attributes gives us the convenience of a more personalized visual effect, such as defining a component, defining a theme, etc.


Android Implements Night Mode summary

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.