public class SelectFile {
    public static final int TYPE_ChooseFile = 0;
    public static final int TYPE_ChooseFolder = 1;

    private final String DefaultPath;
    private final int resultcode;
    private final int type;
    private String FileType = null;

    public SelectFile(int resultcode, int choosetype) {
        this.resultcode = resultcode;
        this.type = choosetype;
        this.DefaultPath = Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    public SelectFile(int resultcode, int choosetype, String path) {
        this.resultcode = resultcode;
        this.type = choosetype;
        this.DefaultPath = path;
    }

    public void setFileType(String ExtraName) {
        this.FileType = ExtraName;
    }

    public void start(Activity act) {
        Intent intent = new Intent(act, FileList.class);
        intent.putExtra("DefaultPath", DefaultPath);
        intent.putExtra("ResultCode", resultcode);
        intent.putExtra("ChooseType", type);
        intent.putExtra("FileType", FileType);
        act.startActivityForResult(intent, resultcode);
    }
} public class ActivityMethod {

    //文件大小格式
    public static String formatSize(Context ctx, String target_size) {
        if (target_size != null) {
            return Formatter.formatFileSize(ctx, Long.valueOf(target_size));
        } else {
            return "0B";
        }
    }

    //获取后缀名
    public static String getExtraName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return "No_Name";
    }

    //包名排序
    public static void orderPackageList(final Context ctx, List<PackageInfo> list) {
        Collections.sort(list, new Comparator<PackageInfo>() {
            @Override
            public int compare(PackageInfo o1, PackageInfo o2) {
                String str1 = o1.applicationInfo.loadLabel(ctx.getPackageManager()).toString();
                String str2 = o2.applicationInfo.loadLabel(ctx.getPackageManager()).toString();
                return str1.compareTo(str2);
            }
        });
    }

    //辅助服务是否打开
    public static boolean isAccessibilitySettingsOn(Context context) {
        int accessibilityEnabled = 0;
        try {
            accessibilityEnabled = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ACCESSIBILITY_ENABLED);
        } catch (Settings.SettingNotFoundException e) {
            e.printStackTrace();
        }
        if (accessibilityEnabled == 1) {
            String services = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES);
            if (services != null) {
                return services.toLowerCase().contains(context.getPackageName().toLowerCase());
            }
        }
        return false;
    }

    //通知监听是否打开
    public static boolean isNotificationListenerEnabled(Context ctx) {
        String pkgName = ctx.getPackageName();
        final String flat = Settings.Secure.getString(ctx.getContentResolver(), "enabled_notification_listeners");
        if (!TextUtils.isEmpty(flat)) {
            final String[] names = flat.split(":");
            for (String name : names) {
                final ComponentName cn = ComponentName.unflattenFromString(name);
                if (cn != null) {
                    if (TextUtils.equals(pkgName, cn.getPackageName())) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    //网络是否可用
    public static boolean isNetworkAvailable(Context ctx) {
        ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = cm.getActiveNetworkInfo();
        return !(networkInfo == null || !networkInfo.isAvailable());
    }

    //获取版本名
    public static String getVersionName(Context context) {
        PackageInfo pinfo = getPackageInfo(context);
        if (pinfo != null) {
            return pinfo.versionName;
        } else {
            return null;
        }
    }

    //获取版本号
    public static int getVersionCode(Context context) {
        PackageInfo pinfo = getPackageInfo(context);
        if (pinfo != null) {
            return pinfo.versionCode;
        } else {
            return 0;
        }
    }

    private static PackageInfo getPackageInfo(Context context) {
        try {
            PackageManager pm = context.getPackageManager();
            return pm.getPackageInfo(context.getPackageName(), PackageManager.GET_CONFIGURATIONS);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
} public class FloatManageMethod {
    private static boolean waitdoubleclick = false;
    private static Handler waithandle;
    private static Runnable waitrun;

    //删除下载的文件(一天前)
    public static void DeleteDownloadFile() {
        long time = System.currentTimeMillis();
        File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/FloatText/Download/");
        if (file.isDirectory() && file.exists()) {
            File[] apks = file.listFiles();
            for (File apk : apks) {
                if (time - apk.lastModified() > 1000 * 60 * 60 * 24) {
                    //noinspection ResultOfMethodCallIgnored
                    apk.delete();
                }
            }
        }
    }

    //自动检测更新
    public static void AutoCheckUpdate(Context ctx) {
        if (ActivityMethod.isNetworkAvailable(ctx)) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
            SharedPreferences spa = ctx.getSharedPreferences("ApplicationSettings", Context.MODE_PRIVATE);
            if (sp.getBoolean("AutoCheckUpdate", false)) {
                if ((System.currentTimeMillis() - spa.getLong("LastUpdateCheckTime", 0) >= 1000 * 60 * 60)) {
                    spa.edit().putLong("LastUpdateCheckTime", System.currentTimeMillis()).apply();
                    GithubUpdateCheck gu = new GithubUpdateCheck(ctx);
                    gu.setProjectData("XFY9326", "FloatText");
                    gu.setMarketDownload(true, "http://www.coolapk.com/apk/tool.xfy9326.floattext");
                    gu.showUpdateInfoDialog(false);
                }
            }
        }
    }

    //通知栏更新
    public static void UpdateNotificationCount(Context ctx) {
        NotificationCompat.Builder notification = ((App) ctx.getApplicationContext()).getNotification();
        if (notification != null) {
            RemoteViews rv = ((App) ctx.getApplicationContext()).getRemoteview();
            if (rv != null) {
                NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
                rv.setTextViewText(R.id.textview_notification_win_count, ctx.getString(R.string.notification_win_count, String.valueOf(FloatManageMethod.getWinCount(ctx))));
                notification.setContent(rv);
                nm.notify(StaticNum.ONGONING_NOTIFICATION_ID, notification.build());
            }
        }
    }

    //获取窗口数量
    public static int getWinCount(Context ctx) {
        App utils = (App) ctx.getApplicationContext();
        return utils.getTextutil().getTextShow().size();
    }

    //隐藏和显示全部
    public static void ShoworHideAllWin(Context ctx, boolean showwin, boolean notifycontrolmode) {
        App utils = (App) ctx.getApplicationContext();
        FloatTextUtils textutils = utils.getTextutil();
        ArrayList<Boolean> showFloat = textutils.getShowFloat();
        if (showFloat.size() > 0) {
            for (int i = 0; i < showFloat.size(); i++) {
                if (!notifycontrolmode || textutils.getNotifyControl().get(i)) {
                    showFloat.set(i, showwin);
                    FloatLinearLayout floatLinearLayout = utils.getFrameutil().getFloatlinearlayout().get(i);
                    floatLinearLayout.setShowState(showwin);
                }
            }

            ListViewAdapter adapter = utils.getListviewadapter();
            FloatData dat = new FloatData(ctx);
            dat.savedata();
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    //隐藏和显示单个窗口
    //显示返回true
    @SuppressWarnings("UnusedReturnValue")
    public static boolean ShoworHideWin(Context ctx, int index) {
        boolean result = true;
        App utils = (App) ctx.getApplicationContext();
        FloatTextUtils textutils = utils.getTextutil();
        ArrayList<Boolean> showFloat = textutils.getShowFloat();
        if (index >= 0 && index < showFloat.size() && showFloat.size() != 0) {
            boolean iShowFloat = showFloat.get(index);
            iShowFloat = !showFloat.set(index, !iShowFloat);
            FloatLinearLayout floatLinearLayout = utils.getFrameutil().getFloatlinearlayout().get(index);
            floatLinearLayout.setShowState(iShowFloat);

            result = iShowFloat;

            ListViewAdapter adapter = utils.getListviewadapter();
            FloatData dat = new FloatData(ctx);
            dat.savedata();
            if (adapter != null) {
                adapter.notifyItemChanged(index);
            }
        }
        return result;
    }

    //锁定和解锁全部
    public static void LockorUnlockAllWin(Context ctx, boolean lockwin, boolean notifycontrolmode) {
        App utils = (App) ctx.getApplicationContext();
        FloatTextUtils textutils = utils.getTextutil();
        ArrayList<Boolean> lock = textutils.getLockPosition();
        if (lock.size() > 0) {
            ArrayList<String> position = textutils.getPosition();
            for (int i = 0; i < lock.size(); i++) {
                if (!notifycontrolmode || textutils.getNotifyControl().get(i)) {
                    FloatLinearLayout fll = utils.getFrameutil().getFloatlinearlayout().get(i);
                    fll.setPositionLocked(lockwin);
                    lock.set(i, lockwin);
                    if (lockwin) {
                        position.set(i, fll.getPosition());
                    }
                }
            }

            ListViewAdapter adapter = utils.getListviewadapter();
            FloatData dat = new FloatData(ctx);
            dat.savedata();
            if (adapter != null) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    //锁定或解锁单个窗口
    //锁定返回true
    public static boolean LockorUnlockWin(Context ctx, int index) {
        boolean result = false;
        App utils = (App) ctx.getApplicationContext();
        FloatTextUtils textutils = utils.getTextutil();
        ArrayList<Boolean> lock = textutils.getLockPosition();
        ArrayList<String> position = textutils.getPosition();
        if (index >= 0 && index < lock.size() && lock.size() != 0) {
            FloatLinearLayout fll = utils.getFrameutil().getFloatlinearlayout().get(index);
            if (fll.getPositionLocked()) {
                fll.setPositionLocked(false);
                lock.set(index, false);
                result = false;
            } else {
                fll.setPositionLocked(true);
                lock.set(index, true);
                position.set(index, fll.getPosition());
                result = true;
            }

            FloatData dat = new FloatData(ctx);
            dat.savedata();
            ListViewAdapter adapter = utils.getListviewadapter();
            if (adapter != null) {
                adapter.notifyItemChanged(index);
            }
        }
        return result;
    }

    //导入或导出的权限检查
    public static void TextFileSolve(Activity ctx, int type, int requestcode) {
        if (Build.VERSION.SDK_INT > 22) {
            if (ctx.checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                ctx.requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestcode);
            } else {
                if (type == 0) {
                    FloatManageMethod.exporttxt(ctx);
                } else if (type == 1) {
                    FloatManageMethod.selectFile(ctx);
                }
            }
        } else {
            if (type == 0) {
                FloatManageMethod.exporttxt(ctx);
            } else if (type == 1) {
                FloatManageMethod.selectFile(ctx);
            }
        }
    }

    //根Activity判断
    public static void RootTask(Activity act) {
        if (!act.isTaskRoot()) {
            act.finish();
        }
    }

    //重启应用
    public static void restartApplication(Context ctx, Intent intent) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        if (Build.VERSION.SDK_INT >= 21) {
            ctx.startActivity(intent);
        } else {
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            ctx.startActivity(intent);
        }
        System.exit(0);
    }

    //设置加载窗口
    public static AlertDialog setLoadingDialog(Context ctx) {
        LayoutInflater inflater = LayoutInflater.from(ctx);
        View layout = inflater.inflate(R.layout.dialog_loading, null);
        AlertDialog.Builder dialog = new AlertDialog.Builder(ctx)
                .setView(layout)
                .setCancelable(false);
        return dialog.create();
    }

    //导入文本
    public static boolean importtxt(Context ctx, String path) {
        File file = new File(path);
        App utils = (App) ctx.getApplicationContext();
        String[] lines = IOMethod.readfile(file);
        ArrayList<String> fixline = new ArrayList<>();
        for (String line : lines) {
            if (!Arrays.toString(lines).isEmpty() && !line.replaceAll("\\s+", "").equalsIgnoreCase("") && !line.replace(" ", "").replace("\n", "").equals("")) {
                fixline.add(line);
            }
        }
        if (fixline.size() != 0 && fixline.size() < 100) {
            ArrayList<String> data = utils.getTextData();
            for (int a = 0; a < fixline.size(); a++) {
                data.add(fixline.get(a));
            }
            closeAllWin(ctx);
            FloatData dat = new FloatData(ctx);
            dat.savedata();
            dat.getSaveArrayData();
            dat.savedata();
            return true;
        } else {
            return false;
        }
    }

    //输出文本
    public static void exporttxt(Context ctx) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", ctx.getResources().getConfiguration().locale);
        String path = Environment.getExternalStorageDirectory().toString() + "/FloatText/Export/FloatText>" + sdf.format(new Date()) + ".txt";
        String str = "";
        ArrayList<String> str_arr = ((App) ctx.getApplicationContext()).getTextData();
        for (int i = 0; i < str_arr.size(); i++) {
            str += str_arr.get(i) + "\n";
        }
        if (!str.replace("\n", "").replaceAll("\\s+", "").equalsIgnoreCase("")) {
            IOMethod.writefile(path, str);
            Toast.makeText(ctx, ctx.getString(R.string.text_export_success) + path, Toast.LENGTH_LONG).show();
        } else {
            FloatManage.snackshow((Activity) ctx, ctx.getString(R.string.text_export_error));
        }
    }

    //选择文件
    public static void selectFile(Activity ctx) {
        Toast.makeText(ctx, R.string.text_import_notice, Toast.LENGTH_LONG).show();
        SelectFile sf = new SelectFile(StaticNum.FLOAT_TEXT_IMPORT_CODE, SelectFile.TYPE_ChooseFile);
        sf.start(ctx);
    }

    //关闭所有窗口
    private static void closeAllWin(Context ctx) {
        WindowManager wm = ((App) ctx.getApplicationContext()).getFloatwinmanager();
        ArrayList<FloatLinearLayout> layout = ((App) ctx.getApplicationContext()).getFrameutil().getFloatlinearlayout();
        ArrayList<Boolean> show = ((App) ctx.getApplicationContext()).getTextutil().getShowFloat();
        for (int i = 0; i < layout.size(); i++) {
            if (show.get(i)) {
                wm.removeView(layout.get(i));
            }
        }
    }

    //动态变量列表
    public static void showDList(final Activity ctx) {
        if (((App) ctx.getApplicationContext()).DynamicNumService) {
            final String[] dynamiclist = ctx.getResources().getStringArray(R.array.floatsetting_dynamic_list);
            String[] dynamicname = ctx.getResources().getStringArray(R.array.floatsetting_dynamic_name);
            String[] result = new String[dynamiclist.length + 1];
            for (int i = 0; i < dynamiclist.length; i++) {
                result[i] = "<" + dynamiclist[i] + ">" + "\n" + dynamicname[i];
            }
            result[dynamiclist.length] = ctx.getString(R.string.dynamic_num_tip);
            AlertDialog.Builder list = new AlertDialog.Builder(ctx)
                    .setTitle(R.string.dynamic_list_title)
                    .setItems(result, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int i) {
                            if (i != dynamiclist.length) {
                                ClipboardManager clip = (ClipboardManager) ctx.getSystemService(Context.CLIPBOARD_SERVICE);
                                if (((App) ctx.getApplicationContext()).HtmlMode) {
                                    clip.setText("#" + dynamiclist[i] + "#");
                                } else {
                                    clip.setText("<" + dynamiclist[i] + ">");
                                }
                                Toast.makeText(ctx, R.string.copy_ok, Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
            list.show();
        } else {
            FloatManage.snackshow(ctx, ctx.getString(R.string.dynamicservice_no_open));
        }
    }

    //权限提示
    @TargetApi(Build.VERSION_CODES.M)
    private static void notifypermission(final Activity ctx) {
        if (!Settings.canDrawOverlays(ctx)) {
            ctx.runOnUiThread(new Runnable() {
                public void run() {
                    CoordinatorLayout cl = (CoordinatorLayout) ctx.findViewById(R.id.FloatManage_MainLayout);
                    Snackbar.make(cl, R.string.no_premission, Snackbar.LENGTH_SHORT).setAction(R.string.get_premission, new OnClickListener() {
                        public void onClick(View v) {
                            Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                            intent.setData(Uri.parse("package:" + ctx.getPackageName()));
                            ctx.startActivity(intent);
                        }
                    }).setActionTextColor(Color.RED).show();

                }
            });
        }
    }

    //权限判断与悬浮窗重现
    public static Thread PrepareSave(Activity ctx, Handler han) {
        if (Build.VERSION.SDK_INT >= 23) {
            if (!Settings.canDrawOverlays(ctx)) {
                FloatManageMethod.askforpermission(ctx, StaticNum.RESHOW_PERMISSION_RESULT_CODE);
            } else {
                FloatManageMethod.delayaskforpermission(ctx);
                if (((App) ctx.getApplicationContext()).getTextData().size() > 0) {
                    return FloatManageMethod.Reshow(ctx, han);
                } else {
                    FloatData fd = new FloatData(ctx);
                    fd.savedata();
                }
            }
        } else {
            if (((App) ctx.getApplicationContext()).getTextData().size() > 0) {
                return FloatManageMethod.Reshow(ctx, han);
            } else {
                FloatData fd = new FloatData(ctx);
                fd.savedata();
            }
        }
        return null;
    }

    //关闭应用
    public static void ShutDown(Context ctx) {
        FloatManageMethod.stopservice(ctx);
        App utils = (App) ctx.getApplicationContext();
        utils.setGetSave(false);
        utils.setFloatReshow(true);
        utils.setStartShowWin(false);
        FloatManageMethod.closeAllWin(ctx);
        System.gc();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                System.exit(0);
            }
        }, 100);
    }

    //关闭应用控制(SnackBar)
    public static void SnackShow_CloseApp(final Activity ctx) {
        if (waitdoubleclick) {
            ctx.finish();
            ShutDown(ctx);
        } else {
            CoordinatorLayout cl = (CoordinatorLayout) ctx.findViewById(R.id.FloatManage_MainLayout);
            Snackbar.make(cl, R.string.exit_title, Snackbar.LENGTH_LONG).setAction(R.string.back_to_launcher, new OnClickListener() {
                public void onClick(View v) {
                    ctx.moveTaskToBack(true);
                }
            }).setCallback(new Snackbar.Callback() {
                @Override
                public void onDismissed(Snackbar bar, int i) {
                    waitdoubleclick = false;
                    if (waithandle != null && waitrun != null) {
                        waithandle.removeCallbacks(waitrun);
                    }
                    super.onDismissed(bar, i);
                }
            }).
                    setActionTextColor(Color.RED).show();
            waitdoubleclick = true;
            waithandle = new Handler();
            waitrun = new Runnable() {
                public void run() {
                    waitdoubleclick = false;
                    waithandle = null;
                    waitrun = null;
                }
            };
            waithandle.postDelayed(waitrun, 2200);
        }
    }

    //设置WindowManager
    public static void setWinManager(Context ctx) {
        WindowManager wm = (WindowManager) ctx.getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
        ((App) ctx.getApplicationContext()).setFloatwinmanager(wm);
    }

    //首次请求权限
    public static void first_ask_for_premission(final Context ctx) {
        SharedPreferences setdata = ctx.getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
        SharedPreferences.Editor setedit = setdata.edit();
        if (!setdata.getBoolean("FirstUse_AskForPremission", false)) {
            AlertDialog.Builder asp = new AlertDialog.Builder(ctx)
                    .setTitle(R.string.ask_for_premission)
                    .setMessage(R.string.ask_for_premission_alert)
                    .setNeutralButton(R.string.open_application_set, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int i) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            intent.setData(Uri.parse("package:" + ctx.getPackageName()));
                            ctx.startActivity(intent);
                        }
                    })
                    .setPositiveButton(R.string.done, null);
            asp.show();
            setedit.putBoolean("FirstUse_AskForPremission", true);
            setedit.apply();
        }
    }

    //准备文件夹
    public static void preparefolder() {
        String typeface_path = Environment.getExternalStorageDirectory().toString() + "/FloatText/TTFs";
        File typeface = new File(typeface_path);
        if (!typeface.exists()) {
            //noinspection ResultOfMethodCallIgnored
            typeface.mkdirs();
        }
    }

    //延迟请求权限
    private static void delayaskforpermission(final Activity act) {
        new Handler().postDelayed(new Runnable() {
            public void run() {
                FloatManageMethod.notifypermission(act);
            }
        }, 2000);
    }

    //请求权限
    @TargetApi(Build.VERSION_CODES.M)
    private static void askforpermission(final Activity act, int code) {
        final int askcode = code;
        AlertDialog.Builder dialog = new AlertDialog.Builder(act)
                .setTitle(R.string.ask_for_premission)
                .setMessage(act.getString(R.string.ask_for_premisdion_msg) + act.getString(R.string.reshow_msg))
                .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface p1, int p2) {
                        Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                        intent.setData(Uri.parse("package:" + act.getPackageName()));
                        act.startActivityForResult(intent, askcode);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface p1, int p2) {
                        act.finish();
                        System.exit(0);
                    }
                })
                .setCancelable(false);
        dialog.show();
    }

    //读取并且设置应用所有数据
    public static Thread getSaveData(final Context ctx, final App utils, final SharedPreferences spdata, final Handler han) {
        return new Thread() {
            public void run() {
                FloatData dat = new FloatData(ctx);
                dat.getSaveArrayData();
                utils.setMovingMethod(spdata.getBoolean("TextMovingMethod", false));
                utils.setStayAliveService(spdata.getBoolean("StayAliveService", true));
                utils.setDynamicNumService(spdata.getBoolean("DynamicNumService", false));
                utils.setDevelopMode(spdata.getBoolean("DevelopMode", false));
                utils.setHtmlMode(spdata.getBoolean("HtmlMode", true));
                utils.setListTextHide(spdata.getBoolean("ListTextHide", false));
                utils.setTextFilter(spdata.getBoolean("TextFilter", false));
                han.obtainMessage(0).sendToTarget();
            }
        };
    }

    //重现悬浮窗
    public static Thread Reshow(final Activity ctx, final Handler han) {
        return new Thread() {
            public void run() {
                final App utils = (App) ctx.getApplicationContext();
                final FloatTextUtils textutils = utils.getTextutil();
                ctx.runOnUiThread(new Runnable() {
                    public void run() {
                        Reshow_Create(ctx, utils, textutils, textutils.getTextShow(), textutils.getShowFloat(), textutils.getLockPosition(), textutils.getPosition(), textutils.getTextMove());
                        utils.getListviewadapter().notifyDataSetChanged();
                    }
                });
                if (han != null) {
                    han.obtainMessage(1).sendToTarget();
                }
            }
        };
    }

    public static void Reshow_Create(Context ctx, App utils, FloatTextUtils textutils, ArrayList<String> Text, ArrayList<Boolean> Show, ArrayList<Boolean> Lock, ArrayList<String> Position, ArrayList<Boolean> Move) {
        if (Text.size() != 0) {
            WindowManager wm = utils.getFloatwinmanager();
            for (int i = 0; i < Text.size(); i++) {
                FloatTextView fv = FloatTextSettingMethod.CreateFloatView(ctx, textutils, i);
                FloatLinearLayout fll = FloatTextSettingMethod.CreateLayout(ctx, i);
                fll.changeShowState(Show.get(i));
                String[] ptemp = new String[]{"100", "150"};
                if (Lock.get(i)) {
                    ptemp = Position.get(i).split("_");
                    fll.setAddPosition(Float.parseFloat(ptemp[0]), Float.parseFloat(ptemp[1]));
                }
                WindowManager.LayoutParams layout = FloatTextSettingMethod.CreateFloatLayout(ctx, wm, fv, fll, Float.parseFloat(ptemp[0]), Float.parseFloat(ptemp[1]), textutils, i);
                fll.setFloatLayoutParams(layout);
                fll.setPositionLocked(Lock.get(i));
                fll.setTop(textutils.getAutoTop().get(i));
                if (utils.getMovingMethod()) {
                    fv.setMoving(Move.get(i), 0);
                } else {
                    fv.setMoving(Move.get(i), 1);
                    if (Move.get(i)) {
                        fll.setShowState(false);
                        fll.setShowState(true);
                    }
                }
                FloatTextSettingMethod.savedata(ctx, fv, fll, Text.get(i), layout);
            }
        }
    }

    //字体文件检测
    public static void floattext_typeface_check(Context ctx, boolean alert) {
        SharedPreferences setdata = ctx.getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
        String filename = setdata.getString("DefaultTTFName", "Default");
        if (filename.equalsIgnoreCase("Default")) {
            return;
        } else {
            String typeface_path = Environment.getExternalStorageDirectory().toString() + "/FloatText/TTFs/" + filename + ".ttf";
            String typeface_path2 = Environment.getExternalStorageDirectory().toString() + "/FloatText/TTFs/" + filename + ".TTF";
            File f1 = new File(typeface_path);
            File f2 = new File(typeface_path2);
            if (f1.exists() || f2.exists()) {
                return;
            }
        }
        setdata.edit().putString("DefaultTTFName", "Default").apply();
        if (alert) {
            FloatManage.snackshow((Activity) ctx, ctx.getString(R.string.text_typeface_err));
        }
    }

    //语言设置 数据
    public static void LanguageInit(Activity ctx) {
        SharedPreferences setdata = ctx.getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
        int lan = setdata.getInt("Language", 0);
        LanguageSet(ctx, lan);
    }

    //语言设置 分类
    public static void LanguageSet(Activity ctx, int i) {
        Resources resource = ctx.getResources();
        Configuration config = resource.getConfiguration();
        switch (i) {
            case 0:
                config.locale = Locale.getDefault();
                break;
            case 1:
                config.locale = Locale.SIMPLIFIED_CHINESE;
                break;
            case 2:
                config.locale = Locale.TAIWAN;
                break;
            case 3:
                config.locale = Locale.ENGLISH;
                break;
        }
        ctx.getBaseContext().getResources().updateConfiguration(config, null);
    }

    //启动服务
    public static void startservice(Context ctx) {
        if (((App) ctx.getApplicationContext()).getStayAliveService()) {
            Intent service = new Intent(ctx, FloatWindowStayAliveService.class);
            ctx.startService(service);
            if (ActivityMethod.isAccessibilitySettingsOn(ctx)) {
                Intent asservice = new Intent(ctx, FloatAdvanceTextUpdateService.class);
                ctx.startService(asservice);
            }
            if (ActivityMethod.isNotificationListenerEnabled(ctx)) {
                Intent notifyservice = new Intent(ctx, FloatNotificationListenerService.class);
                ctx.startService(notifyservice);
            }
        }
    }

    //关闭服务
    private static void stopservice(Context ctx) {
        Intent service = new Intent(ctx, FloatWindowStayAliveService.class);
        ctx.stopService(service);
        Intent floatservice = new Intent(ctx, FloatTextUpdateService.class);
        ctx.stopService(floatservice);
        Intent asservice = new Intent(ctx, FloatAdvanceTextUpdateService.class);
        ctx.stopService(asservice);
        Intent notifyservice = new Intent(ctx, FloatNotificationListenerService.class);
        ctx.stopService(notifyservice);
        Intent downloadservice = new Intent(ctx, FloatUpdateService.class);
        ctx.stopService(downloadservice);
    }

    //用户新建悬浮窗时的提示
    public static void addFloatWindow(final Activity ctx, final ArrayList<String> FloatDataName) {
        if (((App) ctx.getApplicationContext()).getDevelopMode()) {
            String[] type = ctx.getResources().getStringArray(R.array.floatmanage_choose);
            AlertDialog.Builder choose = new AlertDialog.Builder(ctx)
                    .setTitle(R.string.choose_float_type)
                    .setItems(type, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            if (which == 0) {
                                Intent intent = new Intent(ctx, FloatTextSetting.class);
                                intent.putExtra("EditID", FloatDataName.size());
                                ctx.startActivityForResult(intent, StaticNum.FLOATTEXT_RESULT_CODE);
                            } else if (which == 1) {
                                Intent intent = new Intent(ctx, FloatWebSetting.class);
                                ctx.startActivity(intent);
                            }
                        }
                    });
            choose.show();
        } else {
            Intent intent = new Intent(ctx, FloatTextSetting.class);
            intent.putExtra("EditID", FloatDataName.size());
            ctx.startActivityForResult(intent, StaticNum.FLOATTEXT_RESULT_CODE);
        }
    }

} public class IOMethod {
    //读取资源文件
    public static String readAssets(Context ctx, String path) {
        String result = "";
        try {
            InputStreamReader inputReader = new InputStreamReader(ctx.getResources().getAssets().open(path));
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line;
            while ((line = bufReader.readLine()) != null) {
                result += line + "\n";
            }
        } catch (IOException e) {
            result = "No Found";
            e.printStackTrace();
        }
        return result;
    }

    //复制文件
    public static boolean CopyFile(File fromFile, File toFile) {
        try {
            InputStream fosfrom = new FileInputStream(fromFile);
            OutputStream fosto = new FileOutputStream(toFile);
            byte bt[] = new byte[1024];
            int c;
            while ((c = fosfrom.read(bt)) > 0) {
                fosto.write(bt, 0, c);
            }
            fosfrom.close();
            fosto.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //读取文件
    public static String[] readfile(File file) {
        ArrayList<String> output = new ArrayList<>();
        try {
            InputStream file_stream = new FileInputStream(file);
            BufferedReader reader = new BufferedReader(new InputStreamReader(file_stream));
            String line;
            while ((line = reader.readLine()) != null) {
                output.add(line);
            }
            reader.close();
            return output.toArray(new String[output.size()]);
        } catch (IOException e) {
            output.add("Failed");
            return output.toArray(new String[output.size()]);
        }
    }

    //写入文件
    public static boolean writefile(String path, String data) {
        try {
            File file = new File(path);
            pathset(path);
            byte[] Bytes = data.getBytes();
            if (file.exists()) {
                if (file.isFile()) {
                    OutputStream writer = new FileOutputStream(file);
                    writer.write(Bytes);
                    writer.close();
                    return true;
                } else {
                    return false;
                }
            } else {
                //noinspection ResultOfMethodCallIgnored
                file.createNewFile();
                OutputStream writer = new FileOutputStream(file);
                writer.write(Bytes);
                writer.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    //设置文件夹
    private static void pathset(String path) {
        String[] dirs = path.split("/");
        String pth = "";
        for (int i = 0; i < dirs.length; i++) {
            if (i != dirs.length - 1) {
                pth += "/" + dirs[i];
            }
        }
        File dir = new File(pth);
        if (!dir.exists()) {
            //noinspection ResultOfMethodCallIgnored
            dir.mkdirs();
        }
    }
} public class FloatAdvanceTextUpdateService extends AccessibilityService {
    private String currentactivity;
    private String notifypkg;
    private String notifymes;
    private String toasts;
    private String oldactivity = "";
    private boolean sentrule = false;
    private App utils;

    @Override
    public void onCreate() {
        utils = ((App) getApplicationContext());
        currentactivity = toasts = notifymes = getString(R.string.loading);
        FloatManageMethod.setWinManager(this);
        super.onCreate();
    }

    @Override
    public void onAccessibilityEvent(AccessibilityEvent event) {
        if (utils.StartShowWin) {
            int eventType = event.getEventType();
            switch (eventType) {
                case AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED:
                    List<CharSequence> text = event.getText();
                    if (!text.isEmpty()) {
                        String str = text.toString();
                        if (!Objects.equals(str, "[]")) {
                            str = str.substring(1, str.length() - 1);
                            sentrule = getRule();
                            if (sentrule) {
                                if (event.getClassName().toString().contains("Toast")) {
                                    toasts = str;
                                } else {
                                    notifymes = str;
                                    notifypkg = event.getClassName().toString();
                                }
                            } else {
                                if (event.getClassName().toString().contains("Toast")) {
                                    toasts = str;
                                }
                            }
                            sendmes();
                        }
                    }
                    break;
                case AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED:
                    if (event.getClassName() != null) {
                        currentactivity = event.getClassName().toString();
                        if (currentactivity.length() >= 7) {
                            if (!currentactivity.substring(0, 7).equalsIgnoreCase("android")) {
                                sendmes();
                            }
                        } else {
                            sendmes();
                        }
                    }
                    break;
            }
        }
    }

    @Override
    public void onInterrupt() {
    }

    private boolean getRule() {
        return !ActivityMethod.isNotificationListenerEnabled(this);
    }

    private void sendmes() {
        Intent intent = new Intent();
        intent.setAction(StaticString.TEXT_ADVANCE_UPDATE_ACTION);
        intent.putExtra("CurrentActivity", currentactivity);
        if (sentrule) {
            intent.putExtra("NotifyMes", notifymes);
            intent.putExtra("NotifyPkg", notifypkg);
        }
        intent.putExtra("Toasts", toasts);
        sendBroadcast(intent);
        updateactivity();
    }

    private void updateactivity() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(FloatAdvanceTextUpdateService.this);
        if (sp.getBoolean("WinFilterSwitch", false)) {
            if (!oldactivity.equalsIgnoreCase(currentactivity)) {
                Intent intent = new Intent();
                intent.setAction(StaticString.ACTIVITY_CHANGE_ACTION);
                intent.putExtra("CurrentActivity", currentactivity);
                sendBroadcast(intent);
                oldactivity = currentactivity;
            }
        }
    }

} @TargetApi(Build.VERSION_CODES.KITKAT)
public class FloatNotificationListenerService extends NotificationListenerService {
    private String notify;
    private String pkg;
    private App utils;

    @Override
    public void onCreate() {
        utils = ((App) getApplicationContext());
        super.onCreate();
    }

    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        if (utils.StartShowWin) {
            Bundle extras = sbn.getNotification().extras;
            String title = extras.getString(Notification.EXTRA_TITLE);
            String text = extras.getString(Notification.EXTRA_TEXT);
            String sum_text = extras.getString(Notification.EXTRA_SUMMARY_TEXT);
            String sub_text = extras.getString(Notification.EXTRA_SUB_TEXT);
            if (title != null) {
                notify = title + (text == null ? "" : ":" + text) + (sum_text == null ? "" : " " + sum_text) + (sub_text == null ? "" : " " + sub_text);
                pkg = sbn.getPackageName();
                sendmes();
            }
        }
        super.onNotificationPosted(sbn);
    }

    @SuppressWarnings("EmptyMethod")
    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        super.onNotificationRemoved(sbn);
    }

    private void sendmes() {
        Intent intent = new Intent();
        intent.setAction(StaticString.TEXT_ADVANCE_UPDATE_ACTION);
        intent.putExtra("NotifyMes", notify);
        intent.putExtra("NotifyPkg", pkg);
        sendBroadcast(intent);
    }

} public class FloatTextUpdateService extends Service {
    private static String[] LIST;
    private static int[] INFO;
    private final BatteryReceiver breceiver = new BatteryReceiver();
    private final AdvanceTextReceiver atr = new AdvanceTextReceiver();
    private final SensorReceiver sreceiver = new SensorReceiver();
    private boolean FloatScreenState = true;
    private int DynamicReloadTime = 1000;
    private Timer timer, slow_timmer = null;
    private SimpleDateFormat sdf12 = null;
    private SimpleDateFormat sdf24 = null;
    private SimpleDateFormat sdf_clock_12 = null;
    private SimpleDateFormat sdf_clock_24 = null;
    private SimpleDateFormat sdf_date = null;
    private SimpleDateFormat sdf_week = null;
    private SimpleDateFormat sdf_sec = null;
    private String time0, time1, time2, time3, time4, time5;
    private String netspeed;
    private String wifisignal;
    private String orientation;
    private Intent timeIntent = null;
    private boolean timer_run = false;
    private boolean nousual_dynamicword = false;
    private boolean high_cpu_use_dynamicword = false;
    private boolean time_dynamicword = false;
    private String cpurate;
    private String meminfo;
    private float lastTotalRxBytes = 0;
    private float lastTotalTxBytes = 0;
    private long lastTimeStamp = 0;
    private String localip;
    private String clipstr;
    private IntentFilter battery_filter = null;
    private String battery_percent;
    private boolean sensor_use_dynamic_word = false;
    private SensorManager msensor = null;
    private Sensor sensor_tem = null;
    private String cputemperature;
    private Sensor sensor_light = null;
    private String sensorlight;
    private Sensor sensor_gravity = null;
    private String sensorgravity;
    private Sensor sensor_pressure = null;
    private String sensorpressure;
    private Sensor sensor_proximity = null;
    private String sensorproximity;
    private Sensor sensor_step = null;
    private int sensorstep = 0;
    private ClipboardManager clip = null;
    private boolean register_sensor = false;
    private String currentactivity;
    private String notifymes;
    private String toasts;
    private String week;
    private String notifypkg;

    private static void SetListKeys(Context ctx) {
        SharedPreferences sp = FloatServiceMethod.setUpdateList(ctx);
        LIST = FloatServiceMethod.StringtoStringArray(sp.getString("LIST", "[]"));
        INFO = FloatServiceMethod.StringtoIntegerArray(sp.getString("INFO", "[]"));
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        init();
        DynamicModeSet();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            if (intent.getBooleanExtra("RELOAD", false)) {
                DynamicModeSet();
            }
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private String[] SetPostKey() {
        String[] PostList = new String[27];
        PostList[0] = time0;
        PostList[1] = time1;
        PostList[2] = time2;
        PostList[3] = time3;
        PostList[4] = time4;
        PostList[5] = cpurate;
        PostList[6] = netspeed;
        PostList[7] = meminfo;
        PostList[8] = localip;
        PostList[9] = battery_percent;
        PostList[10] = sensorlight;
        PostList[11] = sensorgravity;
        PostList[12] = sensorpressure;
        PostList[13] = cputemperature;
        PostList[14] = sensorproximity;
        PostList[15] = sensorstep + "";
        PostList[16] = clipstr;
        PostList[17] = currentactivity;
        PostList[18] = notifymes;
        PostList[19] = toasts;
        PostList[20] = week;
        PostList[21] = "None";
        PostList[22] = time5;
        PostList[23] = orientation;
        PostList[24] = "None";
        PostList[25] = notifypkg;
        PostList[26] = wifisignal;
        return PostList;
    }

    private void setDefaultKey() {
        String str = getString(R.string.dynamic_word_empty);
        time0 = str;
        time1 = str;
        time2 = str;
        time3 = str;
        time4 = str;
        cpurate = str;
        meminfo = str;
        localip = str;
        battery_percent = str;
        cputemperature = str;
        sensorlight = str;
        sensorgravity = str;
        sensorpressure = str;
        sensorproximity = str;
        currentactivity = str;
        notifymes = str;
        toasts = str;
        week = str;
        time5 = str;
        netspeed = str;
        orientation = str;
        clipstr = str;
        wifisignal = str;
        notifypkg = str;
    }

    private void init() {
        IntentFilter adtfilter = new IntentFilter();
        adtfilter.addAction(Intent.ACTION_SCREEN_ON);
        adtfilter.addAction(Intent.ACTION_SCREEN_OFF);
        adtfilter.addAction(StaticString.TEXT_ADVANCE_UPDATE_ACTION);
        registerReceiver(atr, adtfilter);
        sdf12 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss", getResources().getConfiguration().locale);
        sdf24 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", getResources().getConfiguration().locale);
        sdf_clock_12 = new SimpleDateFormat("hh:mm:ss", getResources().getConfiguration().locale);
        sdf_clock_24 = new SimpleDateFormat("HH:mm:ss", getResources().getConfiguration().locale);
        sdf_date = new SimpleDateFormat("yyyy-MM-dd", getResources().getConfiguration().locale);
        sdf_week = new SimpleDateFormat("E", getResources().getConfiguration().locale);
        sdf_sec = new SimpleDateFormat("ss", getResources().getConfiguration().locale);
        timeIntent = new Intent();
        timeIntent.setAction(StaticString.TEXT_UPDATE_ACTION);
        timeIntent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
        lastTotalRxBytes = FloatServiceMethod.getTotalRxBytes(this);
        lastTotalTxBytes = FloatServiceMethod.getTotalTxBytes(this);
        lastTimeStamp = System.currentTimeMillis();
        battery_filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        clip = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        msensor = (SensorManager) getSystemService(SENSOR_SERVICE);
        sensor_tem = msensor.getDefaultSensor(Sensor.TYPE_TEMPERATURE);
        sensor_light = msensor.getDefaultSensor(Sensor.TYPE_LIGHT);
        sensor_gravity = msensor.getDefaultSensor(Sensor.TYPE_GRAVITY);
        sensor_pressure = msensor.getDefaultSensor(Sensor.TYPE_PRESSURE);
        sensor_proximity = msensor.getDefaultSensor(Sensor.TYPE_PROXIMITY);
        sensor_step = msensor.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
        setDefaultKey();
        SetListKeys(this);
        SetReloadTime();
    }

    private void sendBroadcast() {
        Bundle bundle = new Bundle();
        bundle.putStringArray("LIST", LIST);
        bundle.putIntArray("INFO", INFO);
        bundle.putStringArray("DATA", SetPostKey());
        timeIntent.putExtras(bundle);
        sendBroadcast(timeIntent);
    }

    private String getClip() {
        if (clip != null) {
            if (clip.hasPrimaryClip()) {
                ClipData cd = clip.getPrimaryClip();
                CharSequence cq = cd.getItemAt(0).getText();
                if (cq != null) {
                    return cq.toString();
                }
            }
        }
        return getString(R.string.loading);
    }

    private void getTime() {
        Date d = new Date();
        time0 = sdf12.format(d);
        time1 = sdf24.format(d);
        time2 = sdf_clock_12.format(d);
        time3 = sdf_clock_24.format(d);
        time4 = sdf_date.format(d);
        week = sdf_week.format(d);
        time5 = sdf_sec.format(d);
    }

    private void getNetSpeed() {
        float nowTotalRxBytes = FloatServiceMethod.getTotalRxBytes(this);
        float nowTotalTxBytes = FloatServiceMethod.getTotalTxBytes(this);
        long nowTimeStamp = System.currentTimeMillis();
        float upspeed = ((nowTotalTxBytes - lastTotalTxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));
        float downspeed = ((nowTotalRxBytes - lastTotalRxBytes) * 1000 / (nowTimeStamp - lastTimeStamp));
        lastTimeStamp = nowTimeStamp;
        lastTotalRxBytes = nowTotalRxBytes;
        lastTotalTxBytes = nowTotalTxBytes;
        if (FloatServiceMethod.isVpnUsed()) {
            downspeed = downspeed / 2;
            upspeed = upspeed / 2;
        }
        netspeed = FloatServiceMethod.netspeedset(downspeed) + "↓ " + FloatServiceMethod.netspeedset(upspeed) + "↑";
    }

    private void DynamicModeSet() {
        FloatWinModeGet(this);
        if (FloatScreenState) {
            timeropen();
        } else if (timer_run) {
            timerclose();
        }
        if (!sensor_use_dynamic_word && register_sensor) {
            msensor.unregisterListener(sreceiver);
            register_sensor = false;
        }
    }

    private void timeropen() {
        sensorregister();
        if (!timer_run) {
            timer_run = true;
            registerReceiver(breceiver, battery_filter);
            timercommon();
        }
    }

    private void timercommon() {
        timer = new Timer();
        slow_timmer = new Timer();
        slow_timmer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (high_cpu_use_dynamicword) {
                    cpurate = FloatServiceMethod.getProcessCpuRate() + "%";
                    meminfo = FloatServiceMethod.getMeminfo(FloatTextUpdateService.this);
                }
            }
        }, 500, DynamicReloadTime * 2);
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                if (time_dynamicword) {
                    getTime();
                }
                if (nousual_dynamicword) {
                    getNetSpeed();
                    clipstr = getClip();
                    localip = FloatServiceMethod.getIP(FloatTextUpdateService.this);
                    wifisignal = FloatServiceMethod.getWifiSignal(FloatTextUpdateService.this);
                }
                orientation = FloatServiceMethod.judgeOrientation(FloatTextUpdateService.this);
                sendBroadcast();
            }
        }, 200, DynamicReloadTime);
    }

    private void sensorregister() {
        if (sensor_use_dynamic_word && !register_sensor) {
            register_sensor = true;
            msensor.registerListener(sreceiver, sensor_tem, SensorManager.SENSOR_DELAY_UI);
            msensor.registerListener(sreceiver, sensor_light, SensorManager.SENSOR_DELAY_UI);
            msensor.registerListener(sreceiver, sensor_gravity, SensorManager.SENSOR_DELAY_UI);
            msensor.registerListener(sreceiver, sensor_step, SensorManager.SENSOR_DELAY_UI);
            msensor.registerListener(sreceiver, sensor_pressure, SensorManager.SENSOR_DELAY_UI);
            msensor.registerListener(sreceiver, sensor_proximity, SensorManager.SENSOR_DELAY_UI);
        }
    }

    private void timerclose() {
        timer_run = false;
        if (timer != null) {
            timer.cancel();
            slow_timmer.cancel();
            slow_timmer = null;
            timer = null;
            unregisterReceiver(breceiver);
            msensor.unregisterListener(sreceiver);
            register_sensor = false;
        }
    }

    private void SetReloadTime() {
        SharedPreferences setdata = getSharedPreferences("ApplicationSettings", MODE_PRIVATE);
        DynamicReloadTime = setdata.getInt("DynamicReloadTime", 1000);
    }

    @Override
    public void onDestroy() {
        if (timer_run) {
            timer.cancel();
            unregisterReceiver(atr);
            unregisterReceiver(breceiver);
            if (sensor_use_dynamic_word && register_sensor) {
                msensor.unregisterListener(sreceiver);
                register_sensor = false;
            }
        }
        super.onDestroy();
    }

    //动态变量使用检测
    private void FloatWinModeGet(Context ctx) {
        ArrayList<String> list = ((App) ctx.getApplicationContext()).getFloatText();
        String str = list.toString();
        str = str.substring(1, str.length() - 1).trim();
        nousual_dynamicword = FloatServiceMethod.hasWord(str, new String[]{"NetSpeed", "ClipBoard", "WifiSignal", "LocalIP"});
        time_dynamicword = FloatServiceMethod.hasWord(str, new String[]{"SystemTime", "Date", "Clock", "Week", "Second"});
        sensor_use_dynamic_word = FloatServiceMethod.hasWord(str, new String[]{"Sensor"});
        high_cpu_use_dynamicword = FloatServiceMethod.hasWord(str, new String[]{"CPURate", "MemRate"});
    }

    private class AdvanceTextReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context p1, Intent p2) {
            String action = p2.getAction();
            if (Objects.equals(action, Intent.ACTION_SCREEN_ON)) {
                FloatScreenState = true;
                DynamicModeSet();
            } else if (Objects.equals(action, Intent.ACTION_SCREEN_OFF)) {
                FloatScreenState = false;
                DynamicModeSet();
            } else if (Objects.equals(action, StaticString.TEXT_ADVANCE_UPDATE_ACTION)) {
                currentactivity = FloatServiceMethod.fixnull(p2.getStringExtra("CurrentActivity"), currentactivity);
                toasts = FloatServiceMethod.fixnull(p2.getStringExtra("Toasts"), toasts);
                notifymes = FloatServiceMethod.fixnull(p2.getStringExtra("NotifyMes"), notifymes);
                notifypkg = FloatServiceMethod.fixnull(p2.getStringExtra("NotifyPkg"), notifypkg);
            }
        }
    }

    private class BatteryReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int current = intent.getExtras().getInt("level");
            int total = intent.getExtras().getInt("scale");
            battery_percent = (current * 100 / total) + "%";
        }
    }

    private class SensorReceiver implements SensorEventListener {
        private final DecimalFormat df = new DecimalFormat("#0.00");

        @Override
        public void onSensorChanged(SensorEvent p1) {
            if (p1.sensor.getType() == Sensor.TYPE_TEMPERATURE) {
                cputemperature = df.format((float) Math.round(p1.values[0] * 100) / 100) + "℃";
            } else if (p1.sensor.getType() == Sensor.TYPE_LIGHT) {
                sensorlight = df.format((float) Math.round(p1.values[0] * 100) / 100) + "lux";
            } else if (p1.sensor.getType() == Sensor.TYPE_GRAVITY) {
                sensorgravity = "X:" + df.format((float) Math.round(p1.values[0] * 100) / 100) + "m/s² Y:" + df.format((float) Math.round(p1.values[1] * 100) / 100) + "m/s² Z:" + df.format((float) Math.round(p1.values[2] * 100) / 100) + "m/s²";
            } else if (p1.sensor.getType() == Sensor.TYPE_PRESSURE) {
                sensorpressure = df.format((float) Math.round(p1.values[0] * 10000) / 100) + "Pa";
            } else if (p1.sensor.getType() == Sensor.TYPE_PROXIMITY) {
                sensorproximity = df.format((float) Math.round(p1.values[0] * 100) / 100) + "cm";
            } else if (p1.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
                sensorstep++;
            }
        }

        @Override
        public void onAccuracyChanged(Sensor p1, int p2) {
        }

    }
} public class FloatWindowStayAliveService extends Service {
    private ButtonBroadcastReceiver bbr = null;
    private RemoteViews contentview = null;
    private NotificationCompat.Builder notification;

    private static void collapseStatusBar(Context context) {
        try {
            //noinspection WrongConstant
            Object statusBarManager = context.getSystemService("statusbar");
            Method collapse;
            collapse = statusBarManager.getClass().getMethod("collapsePanels");
            collapse.invoke(statusBarManager);
        } catch (Exception localException) {
            localException.printStackTrace();
        }
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
        create_notification();
        FloatManageMethod.setWinManager(this);
    }

    private void create_notification() {
        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (sp.getBoolean("FloatNotification", true)) {
            create_manage_notify(StaticNum.ONGONING_NOTIFICATION_ID);
        } else {
            create_run_notify(StaticNum.ONGONING_NOTIFICATION_ID);
        }

    }

    private void create_run_notify(int id) {
        Notification notify = new Notification();
        startForeground(id, notify);
    }

    private void create_manage_notify(int id) {
        bbr = new ButtonBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(StaticString.NOTIFICATION_BUTTON_ACTION);
        registerReceiver(bbr, filter);

        notification = new NotificationCompat.Builder(this);
        notification.setSmallIcon(R.mipmap.ic_notification);

        SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
        if (!sp.getBoolean("FloatNotificationIcon", true)) {
            notification.setPriority(Notification.PRIORITY_MIN);
        }

        Intent intent = new Intent(this, FloatManage.class);
        PendingIntent pintent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setContentIntent(pintent);

        contentview = new RemoteViews(getPackageName(), R.layout.remotelayout_notification);

        contentview.setTextViewText(R.id.textview_notification_win_count, getString(R.string.notification_win_count, String.valueOf(FloatManageMethod.getWinCount(this))));

        contentview.setImageViewResource(R.id.button_notification_show, R.drawable.ic_eye_off);
        Intent buttonintent_show = new Intent();
        buttonintent_show.setAction(StaticString.NOTIFICATION_BUTTON_ACTION);
        buttonintent_show.putExtra("BUTTON_ID", 0);
        PendingIntent pintent_show = PendingIntent.getBroadcast(this, 0, buttonintent_show, PendingIntent.FLAG_UPDATE_CURRENT);
        contentview.setOnClickPendingIntent(R.id.button_notification_show, pintent_show);

        contentview.setImageViewResource(R.id.button_notification_unlock, R.drawable.ic_notification_lock_outline);
        Intent buttonintent_unlock = new Intent();
        buttonintent_unlock.setAction(StaticString.NOTIFICATION_BUTTON_ACTION);
        buttonintent_unlock.putExtra("BUTTON_ID", 1);
        PendingIntent pintent_unlock = PendingIntent.getBroadcast(this, 1, buttonintent_unlock, PendingIntent.FLAG_UPDATE_CURRENT);
        contentview.setOnClickPendingIntent(R.id.button_notification_unlock, pintent_unlock);

        notification.setContent(contentview);
        ((App) getApplicationContext()).setRemoteview(contentview);
        ((App) getApplicationContext()).setNotification(notification);
        startForeground(id, notification.build());
    }

    @Override
    public void onDestroy() {
        if (bbr != null) {
            unregisterReceiver(bbr);
        }
        stopForeground(true);
        super.onDestroy();
    }

    private class ButtonBroadcastReceiver extends BroadcastReceiver {
        private boolean WinLock = false;
        private boolean WinShow = true;

        @Override
        public void onReceive(Context p1, Intent p2) {
            if (contentview != null && p2.getAction().equals(StaticString.NOTIFICATION_BUTTON_ACTION)) {
                int buttonid = p2.getIntExtra("BUTTON_ID", -1);
                if (buttonid == 0) {
                    FloatManageMethod.ShoworHideAllWin(p1, WinShow, true);
                    WinShow = !WinShow;
                    if (WinShow) {
                        contentview.setImageViewResource(R.id.button_notification_show, R.drawable.ic_eye_off);
                    } else {
                        contentview.setImageViewResource(R.id.button_notification_show, R.drawable.ic_eye);
                    }
                } else if (buttonid == 1) {
                    FloatManageMethod.LockorUnlockAllWin(p1, WinLock, true);
                    WinLock = !WinLock;
                    if (WinLock) {
                        contentview.setImageViewResource(R.id.button_notification_unlock, R.drawable.ic_notification_lock_unlocked_outline);
                    } else {
                        contentview.setImageViewResource(R.id.button_notification_unlock, R.drawable.ic_notification_lock_outline);
                    }
                }
                NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                notification.setContent(contentview);
                nm.notify(StaticNum.ONGONING_NOTIFICATION_ID, notification.build());
                collapseStatusBar(p1);
            }
        }
    }

} public class FormatArrayList {
    public static ArrayList<String> StringToStringArrayList(String str) {
        ArrayList<String> arr = new ArrayList<>();
        if (str.contains("[") && str.length() >= 3) {
            str = str.substring(1, str.length() - 1);
            if (str.contains(",")) {
                String[] temp = str.split(",");
                for (int i = 0; i < temp.length; i++) {
                    if (i != 0) {
                        temp[i] = temp[i].substring(1, temp[i].length());
                    }
                    arr.add(temp[i]);
                }
            } else {
                arr.add(str);
            }
        }
        return arr;
    }

    public static ArrayList<Float> StringToFloatArrayList(String str) {
        ArrayList<Float> arr = new ArrayList<>();
        if (str.contains("[") && str.length() >= 3) {
            str = str.substring(1, str.length() - 1);
            if (str.contains(",")) {
                String[] temp = str.split(",");
                for (int i = 0; i < temp.length; i++) {
                    temp[i] = temp[i].replaceAll("\\s+", "");
                    arr.add(Float.parseFloat(temp[i]));
                }
            } else {
                arr.add(Float.parseFloat(str));
            }
        }
        return arr;
    }

    public static ArrayList<Integer> StringToIntegerArrayList(String str) {
        ArrayList<Integer> arr = new ArrayList<>();
        if (str.contains("[") && str.length() >= 3) {
            str = str.substring(1, str.length() - 1);
            if (str.contains(",")) {
                String[] temp = str.split(",");
                for (int i = 0; i < temp.length; i++) {
                    temp[i] = temp[i].replaceAll("\\s+", "");
                    arr.add(Integer.parseInt(temp[i]));
                }
            } else {
                arr.add(Integer.parseInt(str));
            }
        }
        return arr;
    }

    public static ArrayList<Boolean> StringToBooleanArrayList(String str) {
        ArrayList<Boolean> arr = new ArrayList<>();
        if (str.contains("[") && str.length() >= 3) {
            str = str.substring(1, str.length() - 1);
            if (str.contains(",")) {
                String[] temp = str.split(",");
                for (int i = 0; i < temp.length; i++) {
                    temp[i] = temp[i].replaceAll("\\s+", "");
                    arr.add(Boolean.parseBoolean(temp[i]));
                }
            } else {
                arr.add(Boolean.parseBoolean(str));
            }
        }
        return arr;
    }
} public class App extends Application {
    public boolean FloatWinReshow = true;
    public boolean DynamicNumService = false;
    public boolean HtmlMode = false;
    public boolean ListTextHide = false;
    public boolean GetSave = false;
    public boolean TextFilter = false;
    public boolean StartShowWin = false;
    private boolean MovingMethod = false;
    private boolean StayAliveService = true;
    private boolean DevelopMode = false;
    private FloatTextUtils textutil;
    private FloatFrameUtils frameutil;
    private ListViewAdapter listviewadapter = null;
    private WindowManager floatwinmanager = null;
    private NotificationCompat.Builder notification = null;
    private RemoteViews remoteview = null;

    @Override
    public void onCreate() {
        super.onCreate();
        CrashCatch();
        init();
    }

    private void CrashCatch() {
        //错误报告
        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(this, "FloatText", "tool.xfy9326.floattext.FloatManage", "1069665464@qq.com");
        crashHandler.setOutPutError(false, Environment.getExternalStorageDirectory().getAbsolutePath() + "/FloatText/CrashLog/");
    }

    private void init() {
        textutil = new FloatTextUtils();
        frameutil = new FloatFrameUtils();
    }

    public RemoteViews getRemoteview() {
        return remoteview;
    }

    public void setRemoteview(RemoteViews remoteview) {
        this.remoteview = remoteview;
    }

    public NotificationCompat.Builder getNotification() {
        return notification;
    }

    public void setNotification(NotificationCompat.Builder notification) {
        this.notification = notification;
    }

    public void setStartShowWin(boolean startShowWin) {
        StartShowWin = startShowWin;
    }

    public void setTextFilter(boolean textFilter) {
        TextFilter = textFilter;
    }

    public void setGetSave(boolean b) {
        this.GetSave = b;
    }

    public ListViewAdapter getListviewadapter() {
        return listviewadapter;
    }

    public void setListviewadapter(ListViewAdapter listviewadapter) {
        this.listviewadapter = listviewadapter;
    }

    public WindowManager getFloatwinmanager() {
        return floatwinmanager;
    }

    public void setFloatwinmanager(WindowManager floatwinmanager) {
        this.floatwinmanager = floatwinmanager;
    }

    public void setListTextHide(boolean listTextHide) {
        ListTextHide = listTextHide;
    }

    public boolean getHtmlMode() {
        return HtmlMode;
    }

    public void setHtmlMode(boolean htmlMode) {
        HtmlMode = htmlMode;
    }

    public boolean getDevelopMode() {
        return DevelopMode;
    }

    public void setDevelopMode(boolean developMode) {
        DevelopMode = developMode;
    }

    public boolean getDynamicNumService() {
        return DynamicNumService;
    }

    public void setDynamicNumService(boolean DynamicNumService) {
        this.DynamicNumService = DynamicNumService;
    }

    public boolean getStayAliveService() {
        return StayAliveService;
    }

    public void setStayAliveService(boolean stayAliveService) {
        StayAliveService = stayAliveService;
    }

    public boolean getMovingMethod() {
        return MovingMethod;
    }

    public void setMovingMethod(boolean movingMethod) {
        MovingMethod = movingMethod;
    }

    public void setFloatReshow(boolean bool) {
        FloatWinReshow = bool;
    }

    public ArrayList<String> getFloatText() {
        return frameutil.getFloattext();
    }

    public void setFloatText(ArrayList<String> floattext) {
        frameutil.setFloattext(floattext);
    }

    public ArrayList<String> getTextData() {
        return textutil.getTextShow();
    }

    public FloatTextUtils getTextutil() {
        return textutil;
    }

    public void setTextutil(FloatTextUtils textutil) {
        this.textutil = textutil;
    }

    public FloatFrameUtils getFrameutil() {
        return frameutil;
    }

    public void setFrameutil(FloatFrameUtils frameutil) {
        this.frameutil = frameutil;
    }

} public class FloatData {
    private final SharedPreferences spdatat;
    private final SharedPreferences.Editor speditt;
    private final SharedPreferences spdata;
    private final SharedPreferences.Editor spedit;
    private final App utils;
    private int DataNum = 0;

    public FloatData(Context ctx) {
        utils = ((App) ctx.getApplicationContext());
        spdatat = ctx.getSharedPreferences("FloatTextList", Activity.MODE_PRIVATE);
        speditt = spdatat.edit();
        speditt.apply();
        spdata = ctx.getSharedPreferences("FloatShowList", Activity.MODE_PRIVATE);
        spedit = spdata.edit();
        spedit.apply();
    }

    //Base64转换
    private static ArrayList<String> TextArr_decode(ArrayList<String> str) {
        ArrayList<String> output = new ArrayList<>();
        output.addAll(str);
        if (str.size() > 0) {
            for (int i = 0; i < str.size(); i++) {
                String result;
                try {
                    result = new String(Base64.decode(str.get(i).getBytes(), Base64.NO_WRAP));
                } catch (IllegalArgumentException e1) {
                    try {
                        result = new String(Base64.decode(str.get(i), Base64.DEFAULT));
                    } catch (IllegalArgumentException e2) {
                        result = str.get(i);
                    }
                }
                output.set(i, result);
            }
        }
        return output;
    }

    private static ArrayList<String> TextArr_encode(ArrayList<String> str) {
        ArrayList<String> output = new ArrayList<>();
        output.addAll(str);
        if (str.size() > 0) {
            for (int i = 0; i < str.size(); i++) {
                String result = Base64.encodeToString(str.get(i).getBytes(), Base64.NO_WRAP);
                output.set(i, result);
            }
        }
        return output;
    }

    //保存
    public void savedata() {
        FloatTextUtils textutils = utils.getTextutil();
        spedit.putInt("Version", StaticNum.FloatDataVersion);
        speditt.putString("TextArray", TextArr_encode(textutils.getTextShow()).toString());
        spedit.putString("ColorArray", textutils.getColorShow().toString());
        spedit.putString("ThickArray", textutils.getThickShow().toString());
        spedit.putString("SizeArray", textutils.getSizeShow().toString());
        spedit.putString("ShowArray", textutils.getShowFloat().toString());
        spedit.putString("LockArray", textutils.getLockPosition().toString());
        spedit.putString("PositionArray", textutils.getPosition().toString());
        spedit.putString("TopArray", textutils.getTextTop().toString());
        spedit.putString("AutoTopArray", textutils.getAutoTop().toString());
        spedit.putString("MoveArray", textutils.getTextMove().toString());
        spedit.putString("SpeedArray", textutils.getTextSpeed().toString());
        spedit.putString("ShadowArray", textutils.getTextShadow().toString());
        spedit.putString("ShadowXArray", textutils.getTextShadowX().toString());
        spedit.putString("ShadowYArray", textutils.getTextShadowY().toString());
        spedit.putString("ShadowRadiusArray", textutils.getTextShadowRadius().toString());
        spedit.putString("BackgroundColorArray", textutils.getBackgroundColor().toString());
        spedit.putString("TextShadowColorArray", textutils.getTextShadowColor().toString());
        spedit.putString("FloatSizeArray", textutils.getFloatSize().toString());
        spedit.putString("FloatLongArray", textutils.getFloatLong().toString());
        spedit.putString("FloatWideArray", textutils.getFloatWide().toString());
        spedit.putString("NotifyControlArray", textutils.getNotifyControl().toString());
        spedit.apply();
        speditt.apply();
    }

    //获取
    public void getSaveArrayData() {
        int version = spdata.getInt("Version", 0);
        ArrayList<String> textarr = new ArrayList<>();
        VersionFix_1(version, textarr);
        VersionFix_2(version, textarr);
        VersionFix_4(version, textarr);
        DataNum = textarr.size();
        FloatTextUtils textutils = utils.getTextutil();
        textutils.setTextShow(textarr);
        textutils.setSizeShow(NewFloatKey(spdata.getString("SizeArray", "[]"), "20.0"));
        textutils.setColorShow(NewIntegerKey(spdata.getString("ColorArray", "[]"), "-61441"));
        textutils.setThickShow(NewBooleanKey(spdata.getString("ThickArray", "[]"), "false"));
        textutils.setShowFloat(NewBooleanKey(spdata.getString("ShowArray", "[]"), "true"));
        textutils.setLockPosition(NewBooleanKey(spdata.getString("LockArray", "[]"), "false"));
        textutils.setPosition(NewStringKey(spdata.getString("PositionArray", "[]"), "50_50"));
        textutils.setTextTop(NewBooleanKey(spdata.getString("TopArray", "[]"), "false"));
        textutils.setAutoTop(NewBooleanKey(spdata.getString("AutoTopArray", "[]"), "true"));
        textutils.setTextMove(NewBooleanKey(spdata.getString("MoveArray", "[]"), "false"));
        textutils.setTextSpeed(NewIntegerKey(spdata.getString("SpeedArray", "[]"), "5"));
        textutils.setTextShadow(NewBooleanKey(spdata.getString("ShadowArray", "[]"), "false"));
        textutils.setTextShadowX(NewFloatKey(spdata.getString("ShadowXArray", "[]"), "10.0"));
        textutils.setTextShadowY(NewFloatKey(spdata.getString("ShadowYArray", "[]"), "10.0"));
        textutils.setTextShadowRadius(NewFloatKey(spdata.getString("ShadowRadiusArray", "[]"), "5.0"));
        textutils.setBackgroundColor(NewIntegerKey(spdata.getString("BackgroundColorArray", "[]"), "16777215"));
        textutils.setTextShadowColor(NewIntegerKey(spdata.getString("TextShadowColorArray", "[]"), "1660944384"));
        textutils.setFloatSize(NewBooleanKey(spdata.getString("FloatSizeArray", "[]"), "false"));
        textutils.setFloatLong(NewFloatKey(spdata.getString("FloatLongArray", "[]"), "100"));
        textutils.setFloatWide(NewFloatKey(spdata.getString("FloatWideArray", "[]"), "100"));
        textutils.setNotifyControl(NewBooleanKey(spdata.getString("NotifyControlArray", "[]"), "true"));
        VersionFix_3(version, textutils);
        utils.setTextutil(textutils);
    }

    private void VersionFix_1(int version, ArrayList<String> textarr) {
        String text = spdatat.getString("TextArray", "[]");
        if (version < 1) {
            textarr.addAll(FormatArrayList.StringToStringArrayList(text));
            speditt.putString("TextArray", TextArr_encode(textarr).toString());
            speditt.commit();
            updateVersion(1);
        } else {
            textarr.addAll(TextArr_decode(FormatArrayList.StringToStringArrayList(text)));
        }
    }

    private void VersionFix_2(int version, ArrayList<String> textarr) {
        if (version < 2) {
            String text_v = spdata.getString("TextArray", "[]");
            textarr.clear();
            if (version < 1) {
                textarr.addAll(FormatArrayList.StringToStringArrayList(text_v));
            }
            textarr.addAll(TextArr_decode(FormatArrayList.StringToStringArrayList(text_v)));
            spedit.remove("TextArray");
            speditt.putString("TextArray", TextArr_encode(textarr).toString());
            spedit.commit();
            speditt.commit();
            updateVersion(2);
        }
    }

    private void VersionFix_3(int version, FloatTextUtils textutils) {
        if (version < 3) {
            ArrayList<Float> longtemp = new ArrayList<>();
            longtemp.addAll(textutils.getFloatLong());
            ArrayList<Float> widetemp = new ArrayList<>();
            widetemp.addAll(textutils.getFloatWide());
            textutils.getFloatLong().clear();
            textutils.getFloatLong().addAll(widetemp);
            textutils.getFloatWide().clear();
            textutils.getFloatWide().addAll(longtemp);
            updateVersion(3);
        }
    }

    private void VersionFix_4(int version, ArrayList<String> textarr) {
        if (version < 4) {
            for (int i = 0; i < textarr.size(); i++) {
                if (textarr.get(i).contains("Origination")) {
                    textarr.set(i, textarr.get(i).replace("Origination", "Orientation"));
                }
            }
            speditt.putString("TextArray", TextArr_encode(textarr).toString());
            speditt.commit();
            updateVersion(4);
        }
    }

    //输出
    public boolean OutputData(String path, int VersionCode) {
        String jsonresult;
        JSONObject mainobject = new JSONObject();
        JSONObject dataobject = new JSONObject();
        JSONObject textobject = new JSONObject();
        try {
            textobject.put("TextArray", spdatat.getString("TextArray", "[]"));

            SetTextData(dataobject);

            mainobject.put("FloatText_Version", VersionCode);
            mainobject.put("Data_Version", StaticNum.FloatDataVersion);
            mainobject.put("Text", textobject);
            mainobject.put("Data", dataobject);

            jsonresult = mainobject.toString();
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        return IOMethod.writefile(path, jsonresult);
    }

    private void SetTextData(JSONObject dataobject) throws JSONException {
        xmltojson(dataobject, "SizeArray");
        xmltojson(dataobject, "ColorArray");
        xmltojson(dataobject, "ThickArray");
        xmltojson(dataobject, "ShowArray");
        xmltojson(dataobject, "LockArray");
        xmltojson(dataobject, "PositionArray");
        xmltojson(dataobject, "TopArray");
        xmltojson(dataobject, "AutoTopArray");
        xmltojson(dataobject, "MoveArray");
        xmltojson(dataobject, "SpeedArray");
        xmltojson(dataobject, "ShadowArray");
        xmltojson(dataobject, "ShadowXArray");
        xmltojson(dataobject, "ShadowYArray");
        xmltojson(dataobject, "ShadowRadiusArray");
        xmltojson(dataobject, "BackgroundColorArray");
        xmltojson(dataobject, "TextShadowColorArray");
        xmltojson(dataobject, "FloatSizeArray");
        xmltojson(dataobject, "FloatLongArray");
        xmltojson(dataobject, "FloatWideArray");
        xmltojson(dataobject, "NotifyControlArray");
    }

    //导入
    public boolean InputData(String path) {
        File bak = new File(path);
        if (!bak.exists() && bak.isDirectory()) {
            return false;
        } else {
            String[] data = IOMethod.readfile(bak);
            String str = "";
            for (String aData : data) {
                str += aData;
            }
            return !str.equalsIgnoreCase("Failed") && InputDataAction(str);
        }
    }

    private boolean InputDataAction(String str) {
        if (!Objects.equals(str, "") && !str.startsWith("error")) {
            try {
                JSONObject mainobject = new JSONObject(str);
                //int FloatText_Version = mainobject.getInt("FloatText_Version");
                int Data_Version = mainobject.getInt("Data_Version");
                JSONObject dataobject = mainobject.getJSONObject("Data");
                JSONObject textobject = mainobject.getJSONObject("Text");

                String text = textobject.getString("TextArray");
                String oldtext = spdatat.getString("TextArray", "[]");
                if (oldtext.equalsIgnoreCase("[]")) {
                    oldtext = text;
                } else {
                    oldtext = CombineArrayString(oldtext, text);
                }
                speditt.putString("TextArray", oldtext);

                savetofile(dataobject);

                JsonVersionFix_1(Data_Version);

                spedit.commit();
                speditt.commit();
                return true;
            } catch (JSONException e) {
                e.printStackTrace();
                return false;
            }
        } else {
            return false;
        }
    }

    //导入数据保存
    private void savetofile(JSONObject dataobject) throws JSONException {
        Iterator it = dataobject.keys();
        while (it.hasNext()) {
            String key = it.next().toString();
            if (spdata.contains(key)) {
                String old = spdata.getString(key, "[]");
                String get = dataobject.getString(key);
                if (old.equalsIgnoreCase("[]")) {
                    old = get;
                } else {
                    old = CombineArrayString(old, get);
                }
                spedit.putString(key, old);
            }
        }
    }

    //导入数据合并
    private String CombineArrayString(String a1, String a2) {
        if (a1.length() == 2) {
            return a2;
        }
        return a1.substring(0, a1.length() - 1) + ", " + a2.substring(1, a2.length());
    }

    private void JsonVersionFix_1(int version) {
        if (version < 3) {
            updateVersion(2);
        }
    }

    private void xmltojson(JSONObject obj, String name) throws JSONException {
        obj.put(name, spdata.getString(name, "[]"));
    }

    private void updateVersion(int i) {
        spedit.putInt("Version", i);
        spedit.commit();
    }

    //新的数据值适配
    private ArrayList<String> NewStringKey(String fix, String def) {
        fix = NewKey(fix, def);
        ArrayList<String> res = FormatArrayList.StringToStringArrayList(fix);
        return FixKey(res, def);
    }

    private ArrayList<Integer> NewIntegerKey(String fix, String def) {
        fix = NewKey(fix, def);
        ArrayList<Integer> res = FormatArrayList.StringToIntegerArrayList(fix);
        return FixKey(res, Integer.valueOf(def));
    }

    private ArrayList<Float> NewFloatKey(String fix, String def) {
        fix = NewKey(fix, def);
        ArrayList<Float> res = FormatArrayList.StringToFloatArrayList(fix);
        return FixKey(res, Float.valueOf(def));
    }

    private ArrayList<Boolean> NewBooleanKey(String fix, String def) {
        fix = NewKey(fix, def);
        ArrayList<Boolean> res = FormatArrayList.StringToBooleanArrayList(fix);
        return FixKey(res, Boolean.valueOf(def));
    }

    private String NewKey(String fix, String def) {
        if (fix.equalsIgnoreCase("[]") && DataNum != 0) {
            ArrayList<String> str = new ArrayList<>();
            for (int i = 0; i < DataNum; i++) {
                str.add(def);
            }
            fix = str.toString();
        }
        return fix;
    }

    private ArrayList<String> FixKey(ArrayList<String> str, String def) {
        while (str.size() < DataNum) {
            str.add(def);
        }
        return str;
    }

    private ArrayList<Float> FixKey(ArrayList<Float> str, Float def) {
        while (str.size() < DataNum) {
            str.add(def);
        }
        return str;
    }

    private ArrayList<Integer> FixKey(ArrayList<Integer> str, Integer def) {
        while (str.size() < DataNum) {
            str.add(def);
        }
        return str;
    }

    private ArrayList<Boolean> FixKey(ArrayList<Boolean> str, Boolean def) {
        while (str.size() < DataNum) {
            str.add(def);
        }
        return str;
    }

} public class StaticNum {
    public static final int FloatDataVersion = 4;
    public static final int DYNAMIC_LIST_VERSION = 12;

    public static final int ONGONING_NOTIFICATION_ID = 13;

    public static final int FLOATUPDATE_START_DOWNLOAD = 14;

    public static final int FLOATTEXT_RESULT_CODE = 0;
    public static final int RESHOW_PERMISSION_RESULT_CODE = 1;
    public static final int FLOATSET_RESULT_CODE = 2;
    public static final int FLOAT_TEXT_IMPORT_CODE = 3;
    public static final int FLOAT_TEXT_IMPORT_PERMISSION = 4;
    public static final int FLOAT_TEXT_EXPORT_PERMISSION = 5;
    public static final int FLOAT_TEXT_SYSTEM_PERMISSION = 6;
    public static final int ADVANCE_TEXT_SET = 7;
    public static final int ADVANCE_TEXT_NOTIFICATION_SET = 8;
    public static final int FLOAT_TEXT_GET_TYPEFACE_PERMISSION = 9;
    public static final int FLOAT_TEXT_GET_BACKUP_PERMISSION = 10;
    public static final int FLOAT_TEXT_GET_RECOVER_PERMISSION = 11;
    public static final int FLOAT_TEXT_SELECT_RECOVER_FILE = 12;
}
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.preference.CheckBoxPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import tool.xfy9326.floattext.FileSelector.SelectFile;
import tool.xfy9326.floattext.Method.ActivityMethod;
import tool.xfy9326.floattext.Method.FloatManageMethod;
import tool.xfy9326.floattext.Method.IOMethod;
import tool.xfy9326.floattext.R;
import tool.xfy9326.floattext.Service.FloatAdvanceTextUpdateService;
import tool.xfy9326.floattext.Service.FloatNotificationListenerService;
import tool.xfy9326.floattext.Service.FloatTextUpdateService;
import tool.xfy9326.floattext.Service.FloatWindowStayAliveService;
import tool.xfy9326.floattext.Tool.FormatArrayList;
import tool.xfy9326.floattext.Utils.App;
import tool.xfy9326.floattext.Utils.FloatData;
import tool.xfy9326.floattext.Utils.StaticNum;
package tool.xfy9326.floattext.Activity;




public class GlobalSetActivity extends AppCompatActivity {
    private PrefFragment pref;

    private static void recoverdata(Context ctx, String path) {
        if (path == null) {
            SelectFile sf = new SelectFile(StaticNum.FLOAT_TEXT_SELECT_RECOVER_FILE, SelectFile.TYPE_ChooseFile);
            sf.setFileType("ftbak");
            sf.start((Activity) ctx);
        } else {
            FloatData fd = new FloatData(ctx);
            if (fd.InputData(path)) {
                final Intent intent = ctx.getPackageManager().getLaunchIntentForPackage(ctx.getPackageName());
                intent.putExtra("RecoverText", 1);
                FloatManageMethod.restartApplication(ctx, intent);
            } else {
                Toast.makeText(ctx, R.string.recover_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }

    private static void backupdata(Context ctx) {
        if (((App) ctx.getApplicationContext()).getFloatText().size() == 0) {
            Toast.makeText(ctx, R.string.backup_nofound, Toast.LENGTH_SHORT).show();
        } else {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH:mm:ss", ctx.getResources().getConfiguration().locale);
            String path = Environment.getExternalStorageDirectory().toString() + "/FloatText/Backup/FloatText>" + sdf.format(new Date()) + ".ftbak";
            FloatData fd = new FloatData(ctx);
            if (fd.OutputData(path, ActivityMethod.getVersionCode(ctx))) {