title: System Wide Wake Lock and release depending on power connection
body: <p>I am trying to work on a simple android app that when the device is plugged in, i.e. via a dock, the screen aquires a wake lock so that the screen does not turn off, no matter what app their in, and when unplugged the wake lock is released. </p>
  
  <p>At the moment I don't have any service runing as I was thinking it wasn't needed. It receives the broadcast intent for power connected and power disconnected. When the power is connected it seems to successfully aquires the wake lock but when the power is disconnected it tries to release the wake lock but instead throws a null pointer exception. I am guessing its because the app isn't necessarily running and there is no service so the variable doesn't get kept. </p>
  
  <p>Below is the code I am using that receives the broadcasts.</p>
  
  <pre><code>public class BroadcastReceiveDetection extends BroadcastReceiver {
  
      @Override
      public void onReceive(Context context, Intent intent) 
      {
          ManageScreenLight manageScreenLight = new ManageScreenLight(context);
          String action = intent.getAction();
  
          if (action == Intent.ACTION_POWER_CONNECTED)
          {
              manageScreenLight.receivedPowerConnected();
          }
          else if (action == Intent.ACTION_POWER_DISCONNECTED)
          {
              try {
                  manageScreenLight.receivedPowerDisconnected();
              } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
              }
          }
      }
  }
  </code></pre>
  
  <p>Below is the code that aquires and releases the wake lock.</p>
  
  <pre><code>Context context;
      PowerManager.WakeLock wakeLock;
      public ManageScreenLight(Context context)
      {
          this.context = context;
      }
  
      public void receivedPowerConnected()
      {
          Toast.makeText(context, "Power connected", Toast.LENGTH_LONG).show();
  
          PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
          wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "ScreenStay");
          wakeLock.acquire();
      }
  
          public void receivedPowerDisconnected() throws IOException
  {
      try
      {
          Toast.makeText(context, "Power disconnected", Toast.LENGTH_LONG).show();
          wakeLock.release();
      }
      catch (Exception ex)
      {
          Toast.makeText(context, ex.toString(), Toast.LENGTH_LONG).show();
      }
  }
  </code></pre>
  
  <p>Is there a way that this can work I would there need to be a service that is running when the wake lock is aquired, and once power is disconnected release and stop the service. </p>
  
  <p>Thanks for any help you can provide. </p>