title: Activity.startLockTask() occasionally throws IllegalArgumentException
body: <p>I currently have a periodic issue where I get an <code>IllegalArgumentException</code> when I call <code>Activity.startLockTask()</code>. My app has a device owner app installed which has allowed my package to automatically pin itself.</p>
  
  <p>The code below is checking to make sure my package can lock itself. If it can then it pins itself.</p>
  
  <p>Code:</p>
  
  <pre><code>if (dpm.isLockTaskPermitted(getPackageName())) {
      super.startLockTask();
  }
  </code></pre>
  
  <p>Logcat:</p>
  
  <pre><code>java.lang.IllegalArgumentException: Invalid task, not in foreground
      at android.os.Parcel.readException(Parcel.java:1544)
      at android.os.Parcel.readException(Parcel.java:1493)
      at android.app.ActivityManagerProxy.startLockTaskMode(ActivityManagerNative.java:5223)
      at android.app.Activity.startLockTask(Activity.java:6163)
  </code></pre>
  
  <p>The issue is my app needs to occasionally restart itself. So we unpin, finish the activity and start it again with a new task, and then exit our process. When the activity comes back up it tries to pin itself - sometimes it works - sometimes it doesn't. I believe how we restart is probably the reason the exception is thrown but it shouldn't matter since the new activity IS in the foreground and IS focused.</p>
  
  <p>Once the activity fails to pin it will continue to fail as long as it tries: If I sit there and try and pin the task every 5 seconds it will continue to fail each time. I've tried pinning in <code>onCreate</code>, <code>onWindowFocusChanged</code>, <code>onResume</code>, and <code>onStart</code>.</p>
  
  <p>Does anyone know what the issue might be?</p>
  
  <p>For reference:<br>
  Line 8853: <a href="https://android.googlesource.com/platform/frameworks/base/+/android-5.0.2_r1/services/core/java/com/android/server/am/ActivityManagerService.java" rel="noreferrer">https://android.googlesource.com/platform/frameworks/base/+/android-5.0.2_r1/services/core/java/com/android/server/am/ActivityManagerService.java</a></p>