Merge cherrypicks of [9943992, 9944684, 9944054, 9943993, 9944476, 9942363, 9942364, 9942365, 9942367, 9944685, 9944686, 9943217, 9944762, 9944764, 9944481, 9944411, 9944055, 9944056, 9944057] into qt-qpr1-release

Change-Id: I79028754f4eb72b297e36d3bb43927d98b652e52
diff --git a/src/com/android/settings/core/SettingsBaseActivity.java b/src/com/android/settings/core/SettingsBaseActivity.java
index 5ff81d5..6e37b16 100644
--- a/src/com/android/settings/core/SettingsBaseActivity.java
+++ b/src/com/android/settings/core/SettingsBaseActivity.java
@@ -17,6 +17,7 @@
 
 import android.annotation.LayoutRes;
 import android.annotation.Nullable;
+import android.app.ActivityManager;
 import android.content.BroadcastReceiver;
 import android.content.ComponentName;
 import android.content.Context;
@@ -26,6 +27,7 @@
 import android.content.res.TypedArray;
 import android.os.AsyncTask;
 import android.os.Bundle;
+import android.text.TextUtils;
 import android.util.ArraySet;
 import android.util.Log;
 import android.view.LayoutInflater;
@@ -61,6 +63,10 @@
     @Override
     protected void onCreate(@Nullable Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
+        if (isLockTaskModePinned() && !isSettingsRunOnTop()) {
+            Log.w(TAG, "Devices lock task mode pinned.");
+            finish();
+        }
         final long startTime = System.currentTimeMillis();
         getLifecycle().addObserver(new HideNonSystemOverlayMixin(this));
 
@@ -148,6 +154,20 @@
         }
     }
 
+    private boolean isLockTaskModePinned() {
+        final ActivityManager activityManager =
+            getApplicationContext().getSystemService(ActivityManager.class);
+        return activityManager.getLockTaskModeState() == ActivityManager.LOCK_TASK_MODE_PINNED;
+    }
+
+    private boolean isSettingsRunOnTop() {
+        final ActivityManager activityManager =
+            getApplicationContext().getSystemService(ActivityManager.class);
+        final String taskPkgName = activityManager.getRunningTasks(1 /* maxNum */)
+            .get(0 /* index */).baseActivity.getPackageName();
+        return TextUtils.equals(getPackageName(), taskPkgName);
+    }
+
     /**
      * @return whether or not the enabled state actually changed.
      */