title: Turn the screen OFF when plugged in to AC or USB and Turn it on when removed from the source
body: <p>Before making this as duplicate:: I see a lot of threads supporting this, <strong>but none of them works in waking up or turning the screen on when the screen is completely turned off (or in sleep mode)</strong>.</p>
  
  <p>My aim: when the USB is connected or the device is plugged in to AC power the screen has to turn off (that is happening), and when the power/ USB is unplugged the screen has to turn on back to the app. (not working).</p>
  
  <p><strong>Note:</strong> If the screen is dimmed out to the lowest instead of turning it off we can turn the brightness on back when required, but that is not what I want.</p>
  
  <p>The links that is suppoting this questions are:
  1. <a href="https://stackoverflow.com/questions/3621599/wake-android-device-up">wake-android-device-up</a>
  2. <a href="https://stackoverflow.com/questions/3660464/is-there-a-way-to-force-an-android-device-to-stay-awake">is-there-a-way-to-force-an-android-device-to-stay-awake</a>
  3. <a href="https://stackoverflow.com/questions/9561320/android-how-to-turn-screen-on-and-off-programmatically">android-how-to-turn-screen-on-and-off-programmatically</a>
  4. <a href="https://stackoverflow.com/questions/2891337/turning-on-screen-programmatically">turning-on-screen-programmatically</a>
  5. <a href="https://stackoverflow.com/questions/4352548/how-to-unlock-the-screen-when-broadcastreceiver-is-called">how-to-unlock-the-screen-when-broadcastreceiver-is-called</a></p>
  
  <p><em>Here is the code that I am using It successfully turns the screen OFF, but will not Turn it on.</em> You can also download the code project from : <a href="https://drive.google.com/file/d/0BwCRkER4bNnIRjdvdmNwRkMyWE0/edit?usp=sharing" rel="nofollow noreferrer">Download Here</a></p>
  
  <p><strong>Class Name: MainActivity</strong> </p>
  
  <pre><code>package com.power.screenmode;
  
  import android.app.Activity;
  import android.app.KeyguardManager;
  import android.content.BroadcastReceiver;
  import android.content.Context;
  import android.content.Intent;
  import android.content.IntentFilter;
  import android.os.BatteryManager;
  import android.os.Bundle;
  import android.os.PowerManager;
  import android.os.PowerManager.WakeLock;
  import android.util.Log;
  import android.view.WindowManager;
  import android.widget.TextView;
  import com.power.screenmode.BackgroundService.PowerUtil;
  
  public class MainActivity extends Activity {
  
  private TextView txt_PowerConnected;
  private boolean isChargerConnected = false;
  private Context mContext;
  private WindowManager.LayoutParams params ;
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
  
      firstLoad();
      initViews();
      doTask();
      startService();
  
  }
  
  @Override
  protected void onResume() {
     //   powerMethod();
      super.onResume();
  }
  
  private void firstLoad(){
      mContext = MainActivity.this;
  }
  
  private void initViews(){
      setContentView(R.layout.activity_main);
      txt_PowerConnected = (TextView)findViewById(R.id.txt_PowerConnected);
  }
  
  private void doTask(){
      isChargerConnected = PowerUtil.isConnected(mContext);
      params = getWindow().getAttributes();
      if(isChargerConnected){
          txt_PowerConnected.setText("Charger Connected");
          turnScreenOFF();
          System.out.println("Power Connected - doTask");
      }else{
          txt_PowerConnected.setText("Charger Not Connected");
          turnScreenON();
          System.out.println("Power Disconnected - doTask");
      }
  }
  
  private void startService(){
  
      try {
          Intent service = new Intent(this, BackgroundService.class);
          startService(service);
          Log.i("SCREEN_MODE", "background service calling");
          } catch (Exception e) {
              e.printStackTrace();
          }   
  
          // register the receiver to listen to battery change
          this.registerReceiver(this.receiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
  
  private void turnScreenOFF(){
      params = getWindow().getAttributes();
      /** Turn OFF: */
      params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
      params.screenBrightness = 0.0f; // 0.1f to turn the brightness to lowest
      getWindow().setAttributes(params);
  }
  
  private void turnScreenON(){
      params = getWindow().getAttributes();
      /** Turn ON: */
      params.flags = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
      params.screenBrightness = 1.0f;
      getWindow().setAttributes(params);
  
      // I have tried the below method also but it didn't work\\\
  //      powerMethod();
  }
  
  private void powerMethod(){
      KeyguardManager km = (KeyguardManager) mContext.getSystemService(Context.KEYGUARD_SERVICE);
      final KeyguardManager.KeyguardLock kl = km.newKeyguardLock("MyKeyguardLock");
      kl.disableKeyguard();
  
      PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
      WakeLock wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP
              | PowerManager.ON_AFTER_RELEASE, "MyWakeLock");
      wakeLock.acquire();
  
      if(wakeLock.isHeld()){
          wakeLock.release();
      }
  
  }
  BroadcastReceiver receiver = new BroadcastReceiver() {
      public void onReceive(Context context, Intent intent) {
          int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
          if (plugged == BatteryManager.BATTERY_PLUGGED_AC ||plugged == BatteryManager.BATTERY_PLUGGED_USB ){ 
              System.out.println("Charger connected -- receiver");
              turnScreenOFF();
          } else{
              System.out.println("Charger Disconnected -- receiver");
              turnScreenON();
          }
      }
  };
  }
  </code></pre>
  
  <p>The Background service class: </p>
  
  <pre><code>             /**
       * 
       */
      package com.power.screenmode;
  
      import java.util.concurrent.Executors;
      import java.util.concurrent.ScheduledExecutorService;
      import java.util.concurrent.ScheduledFuture;
      import java.util.concurrent.TimeUnit;
  
      import android.app.Service;
      import android.content.Context;
      import android.content.Intent;
      import android.content.IntentFilter;
      import android.os.BatteryManager;
      import android.os.Handler;
      import android.os.IBinder;
      import android.util.Log;
      import android.view.WindowManager;
  
      /**
       * @author Prasildas
       *
       */
      public class BackgroundService extends Service {
  
      public static final int INITDELAY_TASK = 0;
      public static final int INTERVAL_TASK1 = 1; 
      private ScheduledExecutorService scheduler;
      public static ScheduledFuture&lt;?&gt; schedule_Background;
      private Handler tableUpdateHandler;
      WindowManager.LayoutParams params ;
  
      @Override
      public void onCreate() {
          super.onCreate();
          Log.i("SCREEN_MODE", "Started");
          tableUpdateHandler = new Handler();
          scheduler = Executors.newScheduledThreadPool(2);
  
          schedule_Background     = scheduler.scheduleAtFixedRate(task_CheckScreenMode, INITDELAY_TASK, INTERVAL_TASK1, TimeUnit.SECONDS);    
           Log.i("SCREEN_MODE", "Created background service --&gt; Live Mode");
          }
  
  
      /**
       * To stop the background check 
       */
      public void stopBackgroundTask() {
          if (schedule_Background != null) {
              schedule_Background.cancel(true);
          }
  
      }
  
          /** The background task in the service  -- Shaking the cart with the badge numbers updating
           */
          private Runnable task_CheckScreenMode   = new Runnable() {
          @Override
          public void run() {
                  tableUpdateHandler.post(new Runnable() {
                      @Override
                      public void run() {
                          try {
                              PowerUtil.isConnected(getApplicationContext());
                              Log.i("SCREEN_MODE", "background running powerutil");
                          }
                          catch (Exception e) {
                              e.printStackTrace();
                          }
                      }
                  });
              }
          };
  
          public static class PowerUtil {
              public static boolean isConnected(Context context) {
                  Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                  int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                  return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
              }
          }
  
  
  
          @Override 
          public int onStartCommand(Intent intent, int flags, int startId) {
              return super.onStartCommand(intent, flags, startId);
          }
  
          @Override 
          public IBinder onBind(final Intent intent) {
              return null;
          }      
  
          @Override 
          public void onDestroy() {
              Log.i("SCREEN_MODE", "background service task 1 destroyed");
              super.onDestroy();
          }
      }
  </code></pre>
  
  <p>The Manifest File:</p>
  
  <pre><code>        &lt;?xml version="1.0" encoding="utf-8"?&gt;
      &lt;manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.power.screenmode"
          android:versionCode="1"
          android:versionName="1.0" &gt;
  
          &lt;uses-sdk
              android:minSdkVersion="8"
              android:targetSdkVersion="18" /&gt;
  
          &lt;uses-permission android:name="android.permission.WAKE_LOCK" /&gt;
          &lt;uses-permission android:name="android.permission.BATTERY_STATS" /&gt;
          &lt;uses-permission android:name="android.permission.DISABLE_KEYGUARD" /&gt;
  
          &lt;application
              android:allowBackup="true"
              android:icon="@drawable/ic_launcher"
              android:label="@string/app_name"
              android:theme="@style/AppTheme" &gt;
              &lt;activity
                  android:name="com.power.screenmode.MainActivity"
                  android:label="@string/app_name" &gt;
                  &lt;intent-filter&gt;
                      &lt;action android:name="android.intent.action.MAIN" /&gt;
  
                      &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
                  &lt;/intent-filter&gt;
              &lt;/activity&gt;
  
              &lt;service android:name="com.power.screenmode.BackgroundService" &gt;
              &lt;/service&gt;
          &lt;/application&gt;
  
      &lt;/manifest&gt;
  </code></pre>