public interface LoginTypeListener {
    void onResponse(int type);
} public interface MainInterface {
    void callFragment(int ID);

    void clearAllFragments();

    void backToPreviousPage();

    void getPermissions(String[] permissions, OnRequestPermissionsListener listener);

    void setDefaultSmsApp(boolean isDefault, OnRequestPermissionsListener listener);

    void getLoginType(LoginTypeListener listener);
    void setLoginType(int type);
} public interface OnRequestPermissionsListener {
    /**
     * 用户开启权限
     */
    void onGranted();

    /**
     * 用户拒绝打开权限
     */
    void onDenied(@Nullable List<String> deniedPermissions);

    /**
     * 获取权限过程被中断，此处只要重新执行获取权限
     */
    void onRetry();

} public class AddressService extends Service {

    private final static String TAG = "AddressService";
    private TelephonyManager tm;//监听来电
    private MyPhoneStateListener psListener;
    private MyToast mytoast;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "onBind");
        return null;
    }

    @Override
    public void onCreate() {
        Log.d(TAG, "onCreate");
        super.onCreate();
        psListener = new MyPhoneStateListener();
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(psListener, PhoneStateListener.LISTEN_CALL_STATE);
        mytoast = new MyToast(this);
        mytoast.setOnDoubleClickListener(new MyToast.OnDoubleClickListener() {
            @Override
            public void onClick(View v) {
                CLog.d(TAG, "Double clicked!");
            }
        });
        mytoast.setOnClickListener(new MyToast.OnClickListener() {
            @Override
            public void onClick(View v) {
                CLog.d(TAG, "clicked!");

            }
        });
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        //取消监听来电
        tm.listen(psListener, PhoneStateListener.LISTEN_NONE);
        psListener = null;
    }

    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);
            Log.d(TAG, "state " + state + "\nincomingNumber " + incomingNumber);
            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING://铃声响起时,也就是来电时
                    TelephoneUtils.getAddressFromNum(getApplicationContext(), incomingNumber, new TelephoneUtils.Callback() {
                        @Override
                        public void onFinish(String content) {
                            mytoast.showMyToast(content);
                        }
                    });
//                    Toast.makeText(getApplicationContext(), address, Toast.LENGTH_LONG).show();

                    break;
                case TelephonyManager.CALL_STATE_IDLE://电话的空闲状态 e.q. 挂电话, 来电拒接
                    mytoast.dismissMyToast();
                    break;
                case TelephonyManager.CALL_STATE_OFFHOOK://去电时
                    TelephoneUtils.getAddressFromNum(getApplicationContext(), incomingNumber, new TelephoneUtils.Callback() {
                        @Override
                        public void onFinish(String content) {
//                    Toast.makeText(getApplicationContext(), address, Toast.LENGTH_LONG).show();
                            mytoast.showMyToast(content);
                        }
                    });
                    break;
            }
        }


    }
} public class BlockCallsSmsService extends Service {
    private final static String TAG = "BlockCallsSmsReceiver";
    /**
     * Uri获取方法：(必须看源代码)
     * 1.到https://android.googlesource.com/platform/packages/providers/ContactsProvider/+/master/
     * 2.找到platform_packages_providers_contactsprovider项目，并下载
     * 3.打开该项目的Manifest，找到provider的配置（CallLogProvider）
     * 4.找到android:authorities="call_log"（call_log为主机名），后面数据库的表名须看源码
     * 5.打开该项目的com.android.providers.contacts/CallLogProvider.java
     * 6.搜寻urimatcher（Uri匹配器）
     * 7.找到一堆matcher.addURI()...
     */
    private final static Uri database = Uri.parse("content://call_log/calls");//呼叫记录uri的路径
    private InnerSmsReceiver receiver;
    private BlacklistDao dao;
    private TelephonyManager tm;
    private MyPhoneStateListener mpsl;
    private DaoFactory daoF;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        daoF = new DaoFactory();
        dao = (BlacklistDao) daoF.createDao(getApplicationContext(), DaoConstants.BLACKLIST);

        receiver = new InnerSmsReceiver();
        registerReceiver(receiver, new IntentFilter("android.provider.Telephony.SMS_RECEIVED"));

        mpsl = new MyPhoneStateListener();
        tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
        tm.listen(mpsl, PhoneStateListener.LISTEN_CALL_STATE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterReceiver(receiver);
        tm.listen(mpsl, PhoneStateListener.LISTEN_NONE);
    }

    /**
     * 短信广播接收者
     */
    private class InnerSmsReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            CLog.d(TAG, "收到短信啦!");

            //取得手机号码(模版代码)
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            if (pdus != null) {
                for (Object pdu : pdus) {
                    SmsMessage message = SmsMessage.createFromPdu((byte[]) pdu);

                    //获取短信的正文内容
                    String content = message.getMessageBody();
                    //获取短信的发送者
                    String address = message.getOriginatingAddress();
                    CLog.d(TAG, address + "\n" + content);


                    int result = dao.findMode(address);
                    switch (result) {
                        case BlacklistDao.NOT_FOUND:
                            //不是黑名单,不管
                            break;
                        case BlacklistDao.MODE_SMS_BLOCKED:
                            abortBroadcast();
                            CLog.d(TAG, "拦截短信");
                            break;
                        case BlacklistDao.MODE_BOTH_BLOCKED:
                            abortBroadcast();
                            CLog.d(TAG, "拦截短信");
                            break;
                    }
                }
            } else
                CLog.e(TAG, "null pdus");

        }
    }

    /**
     * 来电监听器
     */
    private class MyPhoneStateListener extends PhoneStateListener {
        @Override
        public void onCallStateChanged(int state, String incomingNumber) {
            super.onCallStateChanged(state, incomingNumber);

            switch (state) {
                case TelephonyManager.CALL_STATE_RINGING://铃响
                    CLog.d(TAG, "收到电话(" + incomingNumber + ")啦!");

                    dao = (BlacklistDao) daoF.createDao(getApplicationContext(), DaoConstants.BLACKLIST);
                    int result = dao.findMode(incomingNumber);
                    switch (result) {
                        case BlacklistDao.NOT_FOUND:
                            //不是黑名单,不管
                            break;
                        case BlacklistDao.MODE_CALLS_BLOCKED:
                            CLog.d(TAG, "挂断电话");
                            getContentResolver().registerContentObserver(database, true, new CallLogObserve(new Handler(), incomingNumber));
                            endCall();
                            break;
                        case BlacklistDao.MODE_BOTH_BLOCKED:
                            CLog.d(TAG, "挂断电话");
                            getContentResolver().registerContentObserver(database, true, new CallLogObserve(new Handler(), incomingNumber));
                            endCall();
                            break;
                    }
                    break;
            }
        }

        /**
         * 删除呼叫记录
         * 不能紧接着endCall()调用，
         * 因为endCall()是调用另一个进程（不同线程），所以可能endCall()还没执行完生成CallLog。
         * <p>
         * 呼叫时机：观察呼叫记录数据库内容的变化，变化后再调用。
         * 在com.android.providers.contacts/databases/contacts2.db
         *
         * @param incomingNumber 欲删除的号码
         */
        private void deleteCallLog(String incomingNumber) {

            //Uri rawbase = Uri.parse("content://call_log");
            int result = getContentResolver().delete(database, "number=?", new String[]{incomingNumber});
            CLog.d(TAG, "result:" + result);
        }

        /**
         * 使用反射机制加载被隐藏的方法，在另一个进程运行的远程服务的方法
         */
        private void endCall() {
            //api仍然存在，只是被隐藏而已，所以须使用反射找到方法
            //ServiceManager被隐藏（/** @hide */）所以会报错：Cannot resolve symbol ServiceManager
            //IBinder b =  ServiceManager.getService(Context.TELEPHONY_SERVICE);

            //改用：
            try {
                //加载ServiceManager的字节码
                Class clazz = BlockCallsSmsService.class.getClassLoader().loadClass("android.os.ServiceManager");
                Method method = clazz.getDeclaredMethod("getService", String.class);//呼叫的方法与带入的参数型别
                IBinder b = (IBinder) method.invoke(null, Context.TELEPHONY_SERVICE); //the object on which to call this method (or null for static methods)

                ITelephony.Stub.asInterface(b).endCall();
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        /**
         * 通话记录的内容观察者，一旦数据发生变化则呼叫onChange
         */
        private class CallLogObserve extends ContentObserver {
            String incomingNumber;

            /**
             * Creates a content observer.
             *
             * @param handler The handler to run {@link #onChange} on, or null if none.
             */
            public CallLogObserve(Handler handler, String incomingNumber) {
                super(handler);
                this.incomingNumber = incomingNumber;
            }

            @Override
            public void onChange(boolean selfChange, Uri uri) {
                super.onChange(selfChange, uri);
//                CLog.d(TAG, "onChange:" + selfChange + "/uri:" + uri);
            }

            @Override
            public boolean deliverSelfNotifications() {
                return super.deliverSelfNotifications();
            }

            @Override
            public void onChange(boolean selfChange) {
                super.onChange(selfChange);
//                CLog.d(TAG, "onChange:" + selfChange);
                getContentResolver().unregisterContentObserver(this);
                deleteCallLog(incomingNumber);
            }
        }
    }
} public class WatchDogService extends Service {
    private final static String TAG = "WatchDogService";
    private ActivityManager am;
    private List<ActivityManager.RunningTaskInfo> tasks;
    private String packname;
    private boolean flag = true;//服务销毁时关闭看门狗
    private Client client;
    private String unlockPackname;
    private ScreenOffReceiver sOffReceiver;
    private ScreenOnReceiver sOnReceiver;
    private List<String> protectedApps;
    private Intent intentTypePwd;


    @Override
    public void onCreate() {
        super.onCreate();
        final AppsLockDao dao = new AppsLockDao(WatchDogService.this);
        am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        //注册屏幕状态receiver
        sOffReceiver = new ScreenOffReceiver();
        sOnReceiver = new ScreenOnReceiver();
        registerReceiver(sOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
        registerReceiver(sOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
        CustomReceiver cr = new CustomReceiver() {
            @Override
            public void onBroadcastReceive(Result result) {
                if (result.getString() != null)//接受来自解锁画面传来的值
                    unlockPackname = result.getString();
                else//接受改变数据的请求
                    protectedApps = dao.queryAll();

            }
        };
        client = new Client(WatchDogService.this, cr);
        client.gotMessages(BroadcastActions.STOP_WATCHDOG);
        client.gotMessages(BroadcastActions.UPDATE_WATCHDOG);


        /**
         * 把intent搬出来先初始化，不要放在子线程里再初始，提高效率
         */
        intentTypePwd = new Intent();
        intentTypePwd.setClass(getApplicationContext(), TypePwdActivity.class);
        //因为服务没有任务栈信息，所以必须给activity指定运行的任务栈
        intentTypePwd.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        /**
         * 使用queryAll拿到全部的数据，再用list暂存，以后要查询时就直接查list
         * 查内存的速度比查文件或数据库快10倍以上
         */
        protectedApps = dao.queryAll();

        //取得当前应用程序
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            new Thread() {
                public void run() {
                    while (flag) {//所有应用程序的看门狗都是while true的死循环
                        /**
                         * 每开启一个应用程序就会创建一个任务栈，存放用户开启的activities
                         * （所以当所有的activities都退出后，任务栈就清空了）
                         */
                        tasks = am.getRunningTasks(1);//少query提高效率
                        //拿到栈顶的activity也就是当前运行的activity
                        packname = tasks.get(0).topActivity.getPackageName();
//                        CLog.d(TAG, "当前用户操作：" + packname);//不打印logs提高效率
                        protectApp(packname);
                        try {
                            Thread.sleep(20);//重要代码，用来提高CPU效能
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
        } else {
            new Thread() {
                public void run() {
                    while (flag) {
                        /**
                         * LOLLIPOP以上用getRunningAppProcesses().get(0).processName取代am.getRunningTasks(100).get(0).topActivity.getPackageName()，
                         * 添加权限<uses-permission android:name="android.permission.PACKAGE_USAGE_STATS" tools:ignore="ProtectedPermissions" />
                         */
                        packname = am.getRunningAppProcesses().get(0).processName;
//                        CLog.w(TAG, "当前用户操作：" + packname);//不打印logs提高效率
                        protectApp(packname);

                        try {
                            Thread.sleep(20);//重要代码，用来提高CPU效能
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();


        }
    }

    /**
     * 检查应用是否有被用户指定加密，如果有则弹出解锁画面
     *
     * @param packname 包名
     */
    private void protectApp(String packname) {
        if (protectedApps.contains(packname) && !packname.equals(unlockPackname)) {
//            CLog.d(TAG, "解锁 " + packname);
            //弹出解锁介面
            intentTypePwd.putExtra("packname", packname);
            startActivity(intentTypePwd);
        }
        //不弹出解锁介面
    }


    /**
     * 锁屏时禁用，移除packname，重新上锁
     */
    private class ScreenOffReceiver extends BroadcastReceiver {
        private final static String TAG = "ScreenOffReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
//            CLog.d(TAG, "屏幕关闭了");
            unlockPackname = null;
            flag = false;//省电
        }
    }

    private class ScreenOnReceiver extends BroadcastReceiver {
        private final static String TAG = "ScreenOnReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
//            CLog.d(TAG, "屏幕开启了");
            flag = true;//省电
        }
    }

    @Override
    public void onDestroy() {
        CLog.d(TAG, "onDestroy()");
        flag = false;
        unregisterReceiver(sOffReceiver);
        unregisterReceiver(sOnReceiver);
        client.release();
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
} public class SettingItemView extends RelativeLayout {
    private CheckBox cb_status;
    private TextView tv_desc;
    private TextView tv_title;

    private String title_;
    private String desc_on;
    private String desc_off;

    /**
     * 初始化布局文件
     *
     * @param context
     */
    private void iniView(Context context) {

        //把一个布局文件---》View 并且加载在SettingItemView
        View.inflate(context, R.layout.setting_item_view, this);
        cb_status = (CheckBox) this.findViewById(R.id.cb_status);
        tv_desc = (TextView) this.findViewById(R.id.tv_desc);
        tv_title = (TextView) this.findViewById(R.id.tv_title);

    }

    public SettingItemView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        iniView(context);
    }

    public SettingItemView(Context context, AttributeSet attrs) {
        super(context, attrs);
        iniView(context);
        title_ = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "title_");
        desc_on = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "desc_on");
        desc_off = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "desc_off");
        tv_title.setText(title_);
        tv_desc.setText(desc_off);
    }


    public SettingItemView(Context context) {
        super(context);
        iniView(context);
    }

    /**
     * 校验组合控件是否选中
     */

    public boolean isChecked() {
        return cb_status.isChecked();
    }

    /**
     * 设置组合控件的状态
     */

    public void setChecked(boolean checked) {
        cb_status.setChecked(checked);

        if (checked)
            tv_desc.setText(desc_on);
        else
            tv_desc.setText(desc_off);
    }

    /**
     * 设置 组合控件的描述信息
     */

    public void setDesc(String text) {
        tv_desc.setText(text);
    }


} public class SettingNextView extends RelativeLayout {
    private TextView tv_desc;
    private TextView tv_title;
    private ImageView iv_arrow;
    private String title_;
    private String desc_on;
    private String desc_off;

    /**
     * 初始化布局文件
     *
     * @param context
     */
    private void iniView(Context context) {

        //把一个布局文件---》View 并且加载在SettingItemView
        View.inflate(context, R.layout.setting_next_view, this);
        tv_desc = (TextView) this.findViewById(R.id.tv_desc);
        tv_title = (TextView) this.findViewById(R.id.tv_title);

    }

    public SettingNextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        iniView(context);
    }

    public SettingNextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        iniView(context);
        title_ = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "title_");
        desc_on = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "desc_on");
        desc_off = attrs.getAttributeValue("http://schemas.android.com/apk/com.itheima.mobilesafe", "desc_off");
        tv_title.setText(title_);
        tv_desc.setText(desc_off);
    }


    public SettingNextView(Context context) {
        super(context);
        iniView(context);
    }


    /**
     * 设置 组合控件的描述信息
     */

    public void setDesc(String text) {
        tv_desc.setText(text);
    }


    /**
     * 设置控件的标题
     *
     * @param title
     */
    public void setTitle(String title) {
        tv_title.setText(title);
    }

} public class BroadcastActions {
    public final static String ADMIN_PERMISSION = "ADMIN_PERMISSION";
    public final static String SAFE_PHONE = "SAFE_PHONE";
    public final static String DISABLE_SWIPING = "DISABLE_SWIPING";
    public final static String LOCATION_INFO = "LOCATION_INFO";
    public final static String FINISHED_UNINSTALLING = "FINISHED_UNINSTALLING";
    public final static String STOP_WATCHDOG = "STOP_WATCHDOG";
    public final static String UPDATE_WATCHDOG = "UPDATE_WATCHDOG";
} @SuppressWarnings("unused")
public class CLog {
    private static final boolean DEBUG = BuildConfig.SHOW_LOG;

    public static String getTag() {
        String tag = "";
        final StackTraceElement[] ste = Thread.currentThread().getStackTrace();
        for (int i = 0; i < ste.length; i++) {
            if (ste[i].getMethodName().equals("getTag")) {
                tag = "(" + ste[i + 1].getFileName() + ":" + ste[i + 1].getLineNumber() + ")";
            }
        }
        return tag;
    }

    public static void v(String tab, String message) {
        if (MyApplication.getInstance().getPackageName().contains(".test") || DEBUG) {
            Config.showDebugLog = true;
            Log.v(tab, message);
        }
    }

    public static void d(String tab, String message) {
        if (MyApplication.getInstance().getPackageName().contains(".test") || DEBUG) {
            Config.showDebugLog = true;
            Log.d(tab, message);
        }
    }

    public static void e(String tab, String message) {
        if (MyApplication.getInstance().getPackageName().contains(".test") || DEBUG) {
            Config.showDebugLog = true;
            Log.e(tab, message);
        }
    }

    public static void w(String tab, String message) {
        if (MyApplication.getInstance().getPackageName().contains(".test") || DEBUG) {
            Config.showDebugLog = true;
            Log.w(tab, message);
        }
    }

    public static void i(String tab, String message) {
        if (MyApplication.getInstance().getPackageName().contains(".test") || DEBUG) {
            Config.showDebugLog = true;
            Log.i(tab, message);
        }
    }

} public class Constants {
    //Tags of the fragments
    public final static int ANTI_THEFT_FRAG = 0;
    public final static int APPS_MAG_FRAG = 2;
    public final static int TASK_FRAG = 3;
    public final static int A_TOOLS_FRAG = 7;
    public final static int SETTINGS_FRAG = 8;
    public final static int SETUP1_FRAG = 9;
    public final static int SETUP2_FRAG = 10;
    public final static int SETUP3_FRAG = 11;
    public final static int SETUP4_FRAG = 12;
    public final static int SETUP_FRAG = 13;
    public final static int CONTACTS_FRAG = 14;
    public final static int NUM_ADDRESS_QUERY_FRAG = 15;
    public final static int BLACKLIST_FRAG = 16;
    public final static int TRAFFIC_MAG_FRAG = 17;
    public final static int ANTI_VIRUS_FRAG = 18;
    public final static int CLEAR_CACHE_FRAG = 19;

    //activity request code
    public final static int REQUEST_CODE_ENABLE_ADMIN = 10001;
    public final static int PERMISSION_OVERLAY = 10002;
    public final static int PERMISSION_WRITE_SETTINGS = 10003;
    public final static int CHANGEING_DEFAULT_SMS_APP = 10004;
    public final static int ACCOUNT_KIT_REQ_CODE = 10005;
    public final static int UNINSTASLL_APP = 10006;
    public final static int OPEN_SETTINGS = 10007;
    public final static int ACCESS_PERMISSION = 10008;

    //response code
    public static final int FAILED_TO_SEND = 0;
    public static final int SENT_SUCCESSFULLY = 1;
    public static final int TIMEOUT = 2;

    public static String[] addressBgs = new String[]{"半透明", "活力橙", "卫士蓝", "金属灰", "苹果绿"};
    public static int[] addressBgRes = new int[]{R.drawable.call_locate_white, R.drawable.call_locate_orange, R.drawable.call_locate_blue, R.drawable.call_locate_gray, R.drawable.call_locate_green};

    //Login
    public final static int NONE = 0;
    public final static int ACCOUNTKIT = 1;
    public final static int FB = 2;
    public final static int GOOGLE = 3;
    public final static int SINA = 4;
    public final static int QQ = 5;
    public final static int WEIBO = 6;
    public final static int WECHAT = 7;
    public static String[] loginAccounts = new String[]{"NONE", "AccountKit", "Facebook", "Google", "Sina", "QQ", "Weibo", "WeChat"};
} public class MyAdminManager {
    private Context ctx;
    private DevicePolicyManager dpm;
    private ComponentName myAdmin;

    public MyAdminManager(Context ctx) {
        this.ctx = ctx;
        dpm = (DevicePolicyManager) ctx.getSystemService(Context.DEVICE_POLICY_SERVICE);
        myAdmin = new ComponentName(ctx, MyDeviceAdminReceiver.class);
    }

    /**
     * 取得管理员权限
     */
    public void getAdminPermission() {
        // Launch the activity to have the user enable our admin.
        Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
        intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, myAdmin);
        intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "哥们开启我可以一键锁屏，解放按钮");
        Activity activity = (Activity) ctx;
        activity.startActivityForResult(intent, Constants.REQUEST_CODE_ENABLE_ADMIN);
    }

    /**
     * 锁屏
     */
    public void lockScreen() {
        if (dpm.isAdminActive(myAdmin))
            dpm.lockNow();
        else
            Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show();
    }

    /**
     * 重设锁屏密码
     */
    public void resetScreenPassword(String password) {
        if (dpm.isAdminActive(myAdmin))
            dpm.resetPassword(password, 0);
        else
            Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show();
    }

    /**
     * 清除锁屏密码
     */
    public void unlockScreen() {
        if (dpm.isAdminActive(myAdmin)) {
            dpm.resetPassword("", 0);
        } else
            Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show();
    }

    /**
     * 清除数据
     */
    public void wipeData() {
        if (dpm.isAdminActive(myAdmin)) {
            dpm.wipeData(DevicePolicyManager.WIPE_EXTERNAL_STORAGE);//清除sd card
            dpm.wipeData(0);//恢复出厂设置
        } else
            Toast.makeText(ctx, "哥们还没开启管理员权限", Toast.LENGTH_SHORT).show();
    }

    /**
     * 卸载步骤:
     * 1. 先变成普通软件(清除管理员权限)
     * 2. 正常卸载
     */
    public void unInstall() {
        removeAdmin();

        Intent intent = new Intent(Intent.ACTION_DELETE);
        intent.setData(Uri.parse("package:" + ctx.getPackageName()));
        ctx.startActivity(intent);
    }

    /**
     * 检查管理员权限
     *
     * @return
     */
    public boolean isAdmin() {
        if (dpm.isAdminActive(myAdmin))
            return true;
        else
            return false;
    }

    /**
     * 清除管理员权限
     */
    public void removeAdmin() {
        if (dpm.isAdminActive(myAdmin))
            dpm.removeActiveAdmin(myAdmin);
    }

} public class ServiceUtils {

    /**
     * 校验服务是否运行中
     *
     * @param ctx
     * @param serviceName 完整包名 e.g. com.itheima.mobilesafe.services.AddressService
     * @return
     */
    public static boolean isRunningService(Context ctx, String serviceName) {
        boolean isRunning = false;
        ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> infos = am.getRunningServices(100);//代表取得服务数量的最大值
        for (ActivityManager.RunningServiceInfo info : infos) {
            String runningServiceName = info.service.getClassName();
            if (runningServiceName.equals(serviceName))
                isRunning = true;
        }
        return isRunning;
    }
} public class SpNames {
    //file
    public final static String FILE_CONFIG = "config";

    //parameters
    public final static String loginType = "loginType";
    public final static String configed = "configed";
    public final static String safe_phone = "safe_phone";
    public final static String password = "password";
    public final static String default_sms_app = "default_sms_app";
    public final static String update = "update";
    public final static String address_bg = "address_bg";
    public final static String sim_serial = "sim_serial";
    public final static String longitude = "longitude";
    public final static String latitude = "latitude";
    public final static String accutacy = "accutacy";
    public final static String address_x = "address_x";
    public final static String address_y = "address_y";
    public final static String first_open = "first_open";
} public class AccountKitUtils implements BaseLogin {

    @Override
    public void login(Activity activity, Object TYPE) {
        final Intent intent = new Intent(activity, AccountKitActivity.class);
        AccountKitConfiguration.AccountKitConfigurationBuilder configurationBuilder =
                new AccountKitConfiguration.AccountKitConfigurationBuilder(
                        (LoginType) TYPE,
                        AccountKitActivity.ResponseType.TOKEN); // or .ResponseType.TOKEN
        configurationBuilder.setDefaultCountryCode("TW");
        configurationBuilder.setFacebookNotificationsEnabled(true);
        final AccountKitConfiguration configuration = configurationBuilder.build();
        intent.putExtra(
                AccountKitActivity.ACCOUNT_KIT_ACTIVITY_CONFIGURATION,
                configuration);
        activity.startActivityForResult(intent, Constants.ACCOUNT_KIT_REQ_CODE);
    }

    @Override
    public void logout() {
        AccountKit.logOut();
    }

    @Override
    public boolean isLogin() {
        AccessToken accessToken = AccountKit.getCurrentAccessToken();

        if (accessToken != null)
            return true;
        else
            return false;
    }
} public class UserInfo {
    public static String phoneNumber;
    public static String email;
    public static String id;
}
import android.Manifest;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.facebook.accountkit.Account;
import com.facebook.accountkit.AccountKit;
import com.facebook.accountkit.AccountKitCallback;
import com.facebook.accountkit.AccountKitError;
import com.facebook.accountkit.PhoneNumber;
import com.facebook.accountkit.ui.LoginType;
import com.itheima.mobilesafe.R;
import com.itheima.mobilesafe.interfaces.LoginTypeListener;
import com.itheima.mobilesafe.interfaces.MainInterface;
import com.itheima.mobilesafe.interfaces.OnRequestPermissionsListener;
import com.itheima.mobilesafe.services.AddressService;
import com.itheima.mobilesafe.services.BlockCallsSmsService;
import com.itheima.mobilesafe.services.WatchDogService;
import com.itheima.mobilesafe.ui.SettingItemView;
import com.itheima.mobilesafe.ui.SettingNextView;
import com.itheima.mobilesafe.utils.BroadcastActions;
import com.itheima.mobilesafe.utils.CLog;
import com.itheima.mobilesafe.utils.Constants;
import com.itheima.mobilesafe.utils.MyAdminManager;
import com.itheima.mobilesafe.utils.ServiceUtils;
import com.itheima.mobilesafe.utils.SpNames;
import com.itheima.mobilesafe.utils.login.AccountKitUtils;
import com.itheima.mobilesafe.utils.objects.UserInfo;
import java.util.List;
import tw.com.softworld.messagescenter.Client;
import tw.com.softworld.messagescenter.CustomReceiver;
import tw.com.softworld.messagescenter.Result;

        if (update) {
            //自动升级已经开启
            siv_update.setChecked(true);
        } else {
            //自动升级已经关闭
            siv_update.setChecked(false);
        }
        siv_update.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SharedPreferences.Editor editor = sp.edit();
                //判断是否有选中
                //已经打开自动升级了
                if (siv_update.isChecked()) {
                    siv_update.setChecked(false);
                    editor.putBoolean(SpNames.update, false);
                } else {
                    //没有打开自动升级
                    siv_update.setChecked(true);
                    editor.putBoolean(SpNames.update, true);
                }
                editor.apply();
            }
        });

        boolean block = ServiceUtils.isRunningService(getActivity(), "com.itheima.mobilesafe.services.BlockCallsSmsService");

        if (block) {
            //黑名单拦截已经开启
            siv_block.setChecked(true);
        } else {
            //黑名单拦截已经关闭
            siv_block.setChecked(false);
        }

        siv_block.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                clickSiv_block();
            }
        });

        boolean lockApps = ServiceUtils.isRunningService(getActivity(), "com.itheima.mobilesafe.services.WatchDogService");
        if (lockApps) {
            //应用锁已经开启
            siv_lock_apps.setChecked(true);
        } else {
            //应用锁已经关闭
            siv_lock_apps.setChecked(false);
        }

        siv_lock_apps.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                if (siv_lock_apps.isChecked()) {
                    siv_lock_apps.setChecked(false);
                    getActivity().getApplicationContext().stopService(lockAppsService);
                } else {
                    siv_lock_apps.setChecked(true);
                    getActivity().getApplicationContext().startService(lockAppsService);
                }
            }
        });

        //设置归属地限时框背景
        snv_set_background.setTitle("归属地提示框风格");
        int skin = sp.getInt(SpNames.address_bg, 0);
        snv_set_background.setDesc(Constants.addressBgs[skin]);

        snv_set_background.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出对话框
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setTitle("归属地提示框风格");
                dialog.setSingleChoiceItems(Constants.addressBgs, sp.getInt(SpNames.address_bg, 0), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        snv_set_background.setDesc(Constants.addressBgs[which]);
                        SharedPreferences.Editor editor = sp.edit();
                        editor.putInt(SpNames.address_bg, which);
                        editor.apply();
                        dialog.dismiss();
                    }
                });
                dialog.setNegativeButton("取消", null);
                dialog.show();
            }
        });

        //第三方登入
        snv_login.setTitle("账号登入");
        snv_login.setDesc("尚未登入");
        snv_login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //弹出对话框
                AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
                dialog.setTitle("选择登入方式");
                chosenType = accountType;
                dialog.setSingleChoiceItems(Constants.loginAccounts, accountType, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        chosenType = which;
                    }
                });
                if (accountType == Constants.NONE) {
                    dialog.setPositiveButton("登入", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (chosenType) {
                                case Constants.ACCOUNTKIT://Account kit
                                    if (accountKitUtils.isLogin()) {
                                        AccountKit.getCurrentAccount(new AccountKitCallback<Account>() {
                                            @Override
                                            public void onSuccess(final Account account) {
                                                UserInfo.id = account.getId();