package com.example.onekeylockscreen;

import com.example.onekeylockscreen.R;

import android.app.Activity;
import android.app.KeyguardManager;
import android.app.KeyguardManager.KeyguardLock;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

@SuppressWarnings("deprecation")
public class LockScreen extends Activity {

	private DevicePolicyManager mDevicePolicyManager;
	private ComponentName mComponentName;

	public void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		setContentView(R.layout.activity_main);
		// 获取设备管理服务
		mDevicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
		// 申请权限 LockScreenAdmin 继承自 DeviceAdminReceiver
		mComponentName = new ComponentName(this, LockScreenAdmin.class);
		// 判断该组件是否有系统管理员的权限
		boolean active = mDevicePolicyManager.isAdminActive(mComponentName);
		if (active){   
			lockNow(); // 锁屏
		}
		
		while (true) {
			finish();
			// 启动设备管理(隐式Intent) - 在AndroidManifest.xml中设定相应过滤器
			Intent localIntent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
			// 权限列表
			localIntent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
			
			String settings=getResources().getString(R.string.action_settings); 
			// 描述(additional explanation)
			localIntent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,settings);
			startActivityForResult(localIntent, 1);
			
			return;
		}
	}
	protected void onDestroy() {
		super.onDestroy();
		System.exit(0);
	}
	protected void onActivityResult(int paramInt1, int paramInt2,
			Intent paramIntent) {
		super.onActivityResult(paramInt1, paramInt2, paramIntent);
		System.exit(0);
	}
	
	
	@SuppressWarnings({ })
	private void lockNow() {
        KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
        KeyguardLock kl = km.newKeyguardLock(getPackageName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {

                if (kl != null) {
                        kl.disableKeyguard();
                }
                mDevicePolicyManager.lockNow();
                
                if (kl != null) {
                        kl.reenableKeyguard();
                }
        }
}

}