title: Android - Wake Up and Unlock Device
body: <p><strong>Application description:</strong>
  The application is intended as a safety program for a specific client (not to be deployed publicly). When the application has not detected movement for a certain period of time, the application should sound an alarm and bring itself to the foreground if it is in the background or the device is asleep.</p>
  
  <p><strong>The problem:</strong>
  In the event the device is asleep and locked, we need to wake up and unlock the device. Using various techniques found here on SO and other places, we've been able to (partially) wake and unlock the device, however this ONLY behaves properly when the device is physically plugged in to a computer. If the device is sitting by itself unplugged, and we test the wake-unlock, nothing happens; the device seems to remain asleep, and the application seems to do nothing at all (no alarm).</p>
  
  <p>I have used <a href="https://stackoverflow.com/a/10179932/877472">this post about using PowerManager and KeyguardManager</a>, and <a href="https://stackoverflow.com/a/9193501/877472">this post using window flags.</a></p>
  
  <p>Here is the code presently used to wake the device:</p>
  
  <pre><code>public void wakeDevice() {
      PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
      wakeLock = powerManager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "TAG");
      wakeLock.acquire();
  
      KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
      KeyguardLock keyguardLock = keyguardManager.newKeyguardLock("TAG");
      keyguardLock.disableKeyguard();
      runOnUiThread(new Runnable(){
          public void run(){
              getWindow().addFlags(
                        WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                      | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
                      | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                      | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);                
          }
      });
  }
  </code></pre>
  
  <p>From the comments and posts on some of the other SO questions I've seen / used, it seems as though the PowerManager / KeyguardManager code should have done the trick. Again, as I said before, it does technically work while the device is plugged in via USB to the dev machine, but does absolutely nothing while the device is separated.</p>
  
  <p>Also note this is our first Android application, and so are fully aware we might be completely off on what we are trying to do. Any suggestions are welcome.</p>
  
  <p>So in short, given the code above, why does the device behave so differently based on whether it is plugged in, and what should we change in order to wake and unlock the device as described? Thank you in advance for your assistance!</p>