package com.jackytsang.locktaskmode;

import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.app.admin.SystemUpdatePolicy;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.BatteryManager;
import android.os.Build;
import android.os.UserManager;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private ComponentName deviceAdmin;
    private DevicePolicyManager mDpm;
    private PackageManager mPackageManager;
    private static final String Battery_PLUGGED_ANY = Integer.toString(
            BatteryManager.BATTERY_PLUGGED_AC |
                    BatteryManager.BATTERY_PLUGGED_USB |
                    BatteryManager.BATTERY_PLUGGED_WIRELESS);

    private static final String DONT_STAY_ON = "0";

    private boolean mIsKioskEnabled = false;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        deviceAdmin = new ComponentName(this, AdminReceiver.class);
        mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
        mPackageManager = getPackageManager();
//        setDefaultCosuPolicies(true);


        if (!mDpm.isAdminActive(deviceAdmin)) {
            Toast.makeText(this, getString(R.string.not_device_admin), Toast.LENGTH_SHORT).show();
        }

        if (mDpm.isDeviceOwnerApp(getPackageName())) {
            mDpm.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()});
        } else {
            Toast.makeText(this, getString(R.string.not_device_owner), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();

//        // start lock task mode if it's not already active
//        ActivityManager am = (ActivityManager) getSystemService(
//                Context.ACTIVITY_SERVICE);
//        // ActivityManager.getLockTaskModeState api is not available in pre-M.
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
//            if (!am.isInLockTaskMode()) {
//                startLockTask();
//            }
//        } else {
//            if (am.getLockTaskModeState() ==
//                    ActivityManager.LOCK_TASK_MODE_NONE) {
//                startLockTask();
//            }
//        }
    }

    private void setDefaultCosuPolicies(boolean active) {
        // set user restrictions
        setUserRestriction(UserManager.DISALLOW_SAFE_BOOT, active);
        setUserRestriction(UserManager.DISALLOW_FACTORY_RESET, active);
        setUserRestriction(UserManager.DISALLOW_ADD_USER, active);
        setUserRestriction(UserManager.DISALLOW_MOUNT_PHYSICAL_MEDIA, active);
        setUserRestriction(UserManager.DISALLOW_ADJUST_VOLUME, active);

//        // disable keyguard and status bar
//        mDpm.setKeyguardDisabled(deviceAdmin, active);
//        mDpm.setStatusBarDisabled(deviceAdmin, active);

        // enable STAY_ON_WHILE_PLUGGED_IN
        enableStayOnWhilePluggedIn(active);

        // set System Update policy

//        if (active) {
//            mDpm.setSystemUpdatePolicy(deviceAdmin,
//                    SystemUpdatePolicy.createWindowedInstallPolicy(60, 120));
//        } else {
//            DevicePolicyManager.setSystemUpdatePolicy(deviceAdmin, null);
//        }

        // set this Activity as a lock task package

        mDpm.setLockTaskPackages(deviceAdmin,
                active ? new String[]{getPackageName()} : new String[]{});

        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MAIN);
        intentFilter.addCategory(Intent.CATEGORY_HOME);
        intentFilter.addCategory(Intent.CATEGORY_DEFAULT);

        if (active) {
            // set Cosu activity as home intent receiver so that it is started
            // on reboot
            mDpm.addPersistentPreferredActivity(
                    deviceAdmin, intentFilter, new ComponentName(
                            getPackageName(), MainActivity.class.getName()));
        } else {
            mDpm.clearPackagePersistentPreferredActivities(
                    deviceAdmin, getPackageName());
        }
    }

    private void setUserRestriction(String restriction, boolean disallow) {
        if (disallow) {
            mDpm.addUserRestriction(deviceAdmin,
                    restriction);
        } else {
            mDpm.clearUserRestriction(deviceAdmin,
                    restriction);
        }
    }

    private void enableStayOnWhilePluggedIn(boolean enabled) {
        if (enabled) {
            mDpm.setGlobalSetting(
                    deviceAdmin,
                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN,
                    Battery_PLUGGED_ANY);
        } else {
            mDpm.setGlobalSetting(
                    deviceAdmin,
                    Settings.Global.STAY_ON_WHILE_PLUGGED_IN, DONT_STAY_ON);
        }
    }


    private void enableKioskMode(boolean enabled) {
        try {
            if (enabled) {
                if (mDpm.isLockTaskPermitted(this.getPackageName())) {
                    startLockTask();
                    mIsKioskEnabled = true;
                } else {
                    Toast.makeText(this, getString(R.string.kiosk_not_permitted), Toast.LENGTH_SHORT).show();
                }
            } else {
                stopLockTask();
                mIsKioskEnabled = false;
            }
        } catch (Exception e) {
            // TODO: Log and handle appropriately
        }
    }
}

@@ -744,16 +744,49 @@
 anager;%0A
+    private ActivityManager am;%0A%0A
     priv
@@ -845,24 +845,24 @@
 r.toString(%0A
-
             
@@ -1478,24 +1478,99 @@
 eManager();%0A
+        am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);%0A
 //        se
@@ -2032,687 +2032,8 @@
  %7D%0A%0A
-    @Override%0A    protected void onStart() %7B%0A        super.onStart();%0A%0A//        // start lock task mode if it's not already active%0A//        ActivityManager am = (ActivityManager) getSystemService(%0A//                Context.ACTIVITY_SERVICE);%0A//        // ActivityManager.getLockTaskModeState api is not available in pre-M.%0A//        if (Build.VERSION.SDK_INT %3C Build.VERSION_CODES.M) %7B%0A//            if (!am.isInLockTaskMode()) %7B%0A//                startLockTask();%0A//            %7D%0A//        %7D else %7B%0A//            if (am.getLockTaskModeState() ==%0A//                    ActivityManager.LOCK_TASK_MODE_NONE) %7B%0A//                startLockTask();%0A//            %7D%0A//        %7D%0A    %7D%0A
 %0A   
@@ -4679,39 +4679,173 @@
         if (
+!
 enabled
-) %7B%0A    
+ && am.isInLockTaskMode()) %7B%0A                stopLockTask();%0A                mIsKioskEnabled = false;%0A                return;%0A            %7D%0A%0A
             
@@ -4891,32 +4891,78 @@
 ckageName())) %7B%0A
+                if (!am.isInLockTaskMode()) %7B%0A
                 
@@ -5035,32 +5035,46 @@
                %7D
+%0A            %7D
  else %7B%0A        
@@ -5073,36 +5073,32 @@
                 
-    
 Toast.makeText(t
@@ -5175,120 +5175,8 @@
 ();%0A
-                %7D%0A            %7D else %7B%0A                stopLockTask();%0A                mIsKioskEnabled = false;%0A
     

check if it is in lock task mode