1 principle: This principle is very simple, I believe everyone is more familiar with the graphics rendering process of Android, so it is not introduced, the approximate principle is to modify the brightness of the window, and then achieve the effect of making the screen black, through the monitoring activity
Dispatchtouchevent method to monitor the changes of the screen globally.
2 Solution: Directly on the code, there are comments, can be used as a base class, so you can have all subclasses to achieve this effect.
Package Com.example.test;import Android.app.activity;import Android.os.bundle;import android.os.handler;import Android.os.looper;import Android.view.motionevent;import Android.view.windowmanager;public class BaseActivity Extends Activity {/** * maximum screen brightness */float maxlight;/** * Current Brightness */float currentlight;/** * To control screen brightness */handler handler;/** * delay Time */long denytime = 5 * 1000L; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); InitData ();} private void InitData () {handler = new handler (Looper.getmainlooper ()); maxlight = Getlightness (this);} /** * Set Brightness * * @param context * @param light */void setlight (Activity context, int light) {currentlight = light; Windowmanager.layoutparams locallayoutparams = Context.getwindow (). GetAttributes (); Locallayoutparams.screenbrightness = (light/255.0f); Context.getwindow (). SetAttributes (LocalLayoutParams);} /** * Get Brightness * * @param context * @return */float getlightness (Activity context) {Windowmanager.layoutparams locAllayoutparams = Context.getwindow (). GetAttributes (); Float light = Locallayoutparams.screenbrightness;return Light;} @Overrideprotected void OnPause () {super.onpause (); Stopsleeptask ();} @Overrideprotected void Onresume () {super.onresume (); Startsleeptask ();} @Overridepublic boolean dispatchtouchevent (motionevent ev) {if (currentlight = = 1) {startsleeptask ();} return super.dispatchtouchevent (EV);} /** * Open Hibernation Task */void startsleeptask () {SetLight (this, (int) maxlight); Handler.removecallbacks (Sleepwindowtask); Handler.postdelayed (Sleepwindowtask, denytime);} /** * End Hibernation task */void Stopsleeptask () {handler.removecallbacks (sleepwindowtask);} /** * Hibernation task */runnable sleepwindowtask = new Runnable () {@Overridepublic void run () {setlight (baseactivity.this, 1);};}
"Android" Implementation is similar to Baidu for a long time without the app screen dimmed--Do not modify the system settings permissions