public class AboutActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefFragment()).commit();
        sethome();
    }

    private void sethome() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    public static class PrefFragment extends PreferenceFragment {
        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.activity_about);
            preset();
        }

        private void preset() {
            //版本号
            Preference version = findPreference("Version");
            version.setSummary(ActivityMethod.getVersionName(getActivity()) + " (" + ActivityMethod.getVersionCode(getActivity()) + ")");
            version.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    Toast.makeText(getActivity(), "(ノ=Д=)ノ┻━┻", Toast.LENGTH_SHORT).show();
                    return true;
                }
            });
            //更新检测
            Preference checkupdate = findPreference("CheckUpdate");
            checkupdate.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference pre) {
                    if (ActivityMethod.isNetworkAvailable(getActivity())) {
                        GithubUpdateCheck gu = new GithubUpdateCheck(getActivity());
                        gu.setProjectData("XFY9326", "FloatText");
                        gu.setMarketDownload(true, "http://www.coolapk.com/apk/tool.xfy9326.floattext");
                        gu.showUpdateInfoDialog(true);
                    } else {
                        Toast.makeText(getActivity(), R.string.updater_nointernet, Toast.LENGTH_SHORT).show();
                    }
                    return true;
                }
            });
            //捐赠
            Preference donate = findPreference("Donate");
            donate.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference pre) {
                    DonateList dl = new DonateList(getActivity());
                    dl.show();
                    return true;
                }
            });
            //感谢列表
            Preference thanklist = findPreference("ThankList");
            thanklist.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference pre) {
                    AlertDialog.Builder list = new AlertDialog.Builder(getActivity())
                            .setTitle(R.string.xml_about_thanklist)
                            .setMessage(R.string.thanklist)
                            .setPositiveButton(R.string.done, null);
                    list.show();
                    return true;
                }
            });
        }
    }

} 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))) {
                Toast.makeText(ctx, ctx.getString(R.string.backup_success) + path, Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(ctx, R.string.backup_failed, Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        pref = new PrefFragment();
        getFragmentManager().beginTransaction().replace(android.R.id.content, pref).commit();
        sethome();
    }

    //工具栏和返回按键设置
    private void sethome() {
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    @TargetApi(Build.VERSION_CODES.M)
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == StaticNum.FLOAT_TEXT_GET_TYPEFACE_PERMISSION) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                pref.getTypeFace(pref.findPreference("TextTypeface"));
            } else {
                Toast.makeText(this, R.string.premission_error, Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == StaticNum.FLOAT_TEXT_GET_BACKUP_PERMISSION) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                backupdata(this);
            } else {
                Toast.makeText(this, R.string.premission_error, Toast.LENGTH_SHORT).show();
            }
        } else if (requestCode == StaticNum.FLOAT_TEXT_GET_RECOVER_PERMISSION) {
            if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                recoverdata(this, null);
            } else {
                Toast.makeText(this, R.string.premission_error, Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == StaticNum.ADVANCE_TEXT_SET) {
            Preference adts = pref.findPreference("AdvanceTextService");
            pref.setADTsum(adts);
        } else if (requestCode == StaticNum.ADVANCE_TEXT_NOTIFICATION_SET) {
            Preference nous = pref.findPreference("NotificationListenerService");
            pref.setNOSsum(nous);
        } else if (requestCode == StaticNum.FLOAT_TEXT_SELECT_RECOVER_FILE) {
            if (data != null) {
                String str = data.getStringExtra("FilePath");
                recoverdata(this, str);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    public static class PrefFragment extends PreferenceFragment {
        private String default_typeface;
        private int typeface_choice, language_choice;
        private String[] AppNames, PkgNames;
        private boolean[] AppState;

        @Override
        public void onCreate(@Nullable Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.global_settings);
            ViewSet();
            ServiceViewSet();
            DataViewSet();
        }

        private void ViewSet() {
            //通知栏控制
            CheckBoxPreference notify = (CheckBoxPreference) findPreference("FloatNotification");
            notify.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    StayAliveSet(false);
                    StayAliveSet(true);
                    return true;
                }
            });
            //跑马灯模式
            CheckBoxPreference movemethod = (CheckBoxPreference) findPreference("TextMovingMethod");
            movemethod.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    ((App) getActivity().getApplicationContext()).setMovingMethod((boolean) p2);
                    Toast.makeText(getActivity(), R.string.restart_to_apply, Toast.LENGTH_LONG).show();
                    return true;
                }
            });
            //字体
            Preference typeface = findPreference("TextTypeface");
            final SharedPreferences setdata = getActivity().getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
            default_typeface = setdata.getString("DefaultTTFName", "Default");
            if (default_typeface.equalsIgnoreCase("Default")) {
                default_typeface = getString(R.string.text_default_typeface);
            }
            typeface.setSummary(getString(R.string.xml_global_text_typeface_summary) + default_typeface);
            typeface.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference pre) {
                    DataAction(0, pre, StaticNum.FLOAT_TEXT_GET_TYPEFACE_PERMISSION);
                    return true;
                }
            });
            //语言
            Preference language = findPreference("Language");
            final String[] lan_list = getResources().getStringArray(R.array.language_list);
            language_choice = setdata.getInt("Language", 0);
            language.setSummary(getString(R.string.xml_global_language_sum) + lan_list[language_choice]);
            language.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference pre) {
                    LanguageSet(pre, lan_list);
                    return true;
                }
            });
            //动态变量刷新时间
            Preference dynamictime = findPreference("DynamicTime");
            dynamictime.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    DynamicTimeSet(setdata);
                    return true;
                }
            });
            //实验性功能
            CheckBoxPreference develop = (CheckBoxPreference) findPreference("DevelopMode");
            develop.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    ((App) getActivity().getApplicationContext()).setDevelopMode((boolean) p2);
                    return true;
                }
            });
            //HTML代码功能
            CheckBoxPreference html = (CheckBoxPreference) findPreference("HtmlMode");
            html.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    ((App) getActivity().getApplicationContext()).setHtmlMode((boolean) p2);
                    Toast.makeText(getActivity(), R.string.restart_to_apply, Toast.LENGTH_LONG).show();
                    return true;
                }
            });
            //管理列表单行文字
            CheckBoxPreference hidetext = (CheckBoxPreference) findPreference("ListTextHide");
            hidetext.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    ((App) getActivity().getApplicationContext()).setListTextHide((boolean) p2);
                    return true;
                }
            });
            //窗口过滤器
            Preference filter = findPreference("WinFilter");
            filter.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    FilterSet(setdata);
                    return true;
                }
            });
            //文字过滤器
            CheckBoxPreference textfilter = (CheckBoxPreference) findPreference("TextFilter");
            textfilter.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    ((App) getActivity().getApplicationContext()).setTextFilter((boolean) p2);
                    return true;
                }
            });
            //文字过滤器帮助
            Preference textfilterhelp = findPreference("TextFilterHelp");
            textfilterhelp.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    TextFilterHelpGet(getActivity());
                    return true;
                }
            });
            //通知栏图标设置
            CheckBoxPreference notifyicon = (CheckBoxPreference) findPreference("FloatNotificationIcon");
            notifyicon.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    StayAliveSet(false);
                    StayAliveSet(true);
                    return true;
                }
            });
        }

        private void ServiceViewSet() {
            //进程守护服务
            CheckBoxPreference stayalive = (CheckBoxPreference) findPreference("StayAliveService");
            stayalive.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    StayAliveSet((boolean) p2);
                    return true;
                }
            });
            //动态变量服务
            CheckBoxPreference dynamicnum = (CheckBoxPreference) findPreference("DynamicNumService");
            dynamicnum.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
                public boolean onPreferenceChange(Preference p1, Object p2) {
                    DymanicSet((boolean) p2);
                    return true;
                }
            });
            //高级功能服务
            Preference adts = findPreference("AdvanceTextService");
            setADTsum(adts);
            adts.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    Intent intent = new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS);
                    startActivityForResult(intent, StaticNum.ADVANCE_TEXT_SET);
                    return true;
                }
            });
            //通知监听服务
            Preference nous = findPreference("NotificationListenerService");
            setNOSsum(nous);
            nous.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
                        Intent intent = new Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS);
                        startActivityForResult(intent, StaticNum.ADVANCE_TEXT_NOTIFICATION_SET);
                    }
                    return true;
                }
            });
            //自定义动态变量
            Preference dynamicwordaddon = findPreference("DynamicWordAddon");
            dynamicwordaddon.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    DynamicAddonHelpGet(getActivity());
                    return true;
                }
            });
        }

        private void DynamicTimeSet(final SharedPreferences sp) {
            int num = sp.getInt("DynamicReloadTime", 1000);
            LayoutInflater inflater = LayoutInflater.from(getActivity());
            View view = inflater.inflate(R.layout.dialog_text, null);
            AlertDialog.Builder set = new AlertDialog.Builder(getActivity());
            set.setTitle(R.string.xml_global_dynamicword_reload_time);
            final EditText et = (EditText) view.findViewById(R.id.dialog_text_edittext);
            et.setText(String.valueOf(num));
            et.setKeyListener(new DigitsKeyListener(false, true));
            set.setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface d, int i) {
                    String str = et.getText().toString();
                    if (!str.isEmpty()) {
                        int get = Integer.valueOf(str);
                        if (get < 500) {
                            Toast.makeText(getActivity(), R.string.num_err, Toast.LENGTH_SHORT).show();
                        } else {
                            sp.edit().putInt("DynamicReloadTime", get).apply();
                            Toast.makeText(getActivity(), R.string.restart_to_apply, Toast.LENGTH_LONG).show();
                        }
                    }
                }
            });
            set.setNegativeButton(R.string.cancel, null);
            set.setView(view);
            set.show();
        }

        private void DataViewSet() {
            Preference backup = findPreference("DataBackup");
            backup.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    DataAction(2, p, StaticNum.FLOAT_TEXT_GET_BACKUP_PERMISSION);
                    return true;
                }
            });
            Preference recover = findPreference("DataRecover");
            recover.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                public boolean onPreferenceClick(Preference p) {
                    DataAction(1, p, StaticNum.FLOAT_TEXT_GET_RECOVER_PERMISSION);
                    return true;
                }
            });
        }

        private void DynamicAddonHelpGet(Context ctx) {
            String[] paths = new String[]{"HELPS/Dynamic_Words_Addon_cn.txt", "HELPS/Dynamic_Words_Addon_tw.txt", "HELPS/Dynamic_Words_Addon_en.txt"};
            String path = MultiLanguageSet(ctx, paths);
            String str = IOMethod.readAssets(ctx, path);
            SetHelpDialog(ctx, R.string.xml_global_service_dynamicaddon, str);
        }

        private void TextFilterHelpGet(Context ctx) {
            String[] paths = new String[]{"HELPS/TextFilter_cn.txt", "HELPS/TextFilter_tw.txt", "HELPS/TextFilter_en.txt"};
            String path = MultiLanguageSet(ctx, paths);
            String str = IOMethod.readAssets(ctx, path);
            SetHelpDialog(ctx, R.string.xml_global_text_filter, str);
        }

        private void SetHelpDialog(Context ctx, int title, String str) {
            AlertDialog.Builder help = new AlertDialog.Builder(ctx);
            help.setTitle(title);
            help.setMessage(str);
            help.setPositiveButton(R.string.done, null);
            help.show();
        }

        //语言设置
        private String MultiLanguageSet(Context ctx, String[] arr) {
            String path = arr[2];
            String locale = ctx.getResources().getConfiguration().locale.getCountry();
            if (locale.equals(Locale.SIMPLIFIED_CHINESE.getCountry())) {
                path = arr[0];
            } else if (locale.equals(Locale.TAIWAN.getCountry())) {
                path = arr[1];
            } else if (locale.equals(Locale.ENGLISH.getCountry())) {
                path = arr[2];
            }
            return path;
        }

        private void DataAction(int type, Preference pre, int requestcode) {
            if (Build.VERSION.SDK_INT > 22) {
                if (getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, requestcode);
                } else {
                    if (type == 0) {
                        getTypeFace(pre);
                    } else if (type == 1) {
                        recoverdata(getActivity(), null);
                    } else if (type == 2) {
                        backupdata(getActivity());
                    }
                }
            } else {
                if (type == 0) {
                    getTypeFace(pre);
                } else if (type == 1) {
                    recoverdata(getActivity(), null);
                } else if (type == 2) {
                    backupdata(getActivity());
                }
            }
        }

        private void StayAliveSet(boolean b) {
            ((App) getActivity().getApplicationContext()).setStayAliveService(b);
            Intent service = new Intent(getActivity(), FloatWindowStayAliveService.class);
            if (b) {
                getActivity().startService(service);
            } else {
                FloatManageMethod.setWinManager(getActivity());
                getActivity().stopService(service);
            }
        }

        private void DymanicSet(boolean b) {
            ((App) getActivity().getApplicationContext()).setDynamicNumService(b);
            Intent service = new Intent(getActivity(), FloatTextUpdateService.class);
            Intent asservice = new Intent(getActivity(), FloatAdvanceTextUpdateService.class);
            Intent notifyservice = new Intent(getActivity(), FloatNotificationListenerService.class);
            if (b) {
                getActivity().startService(service);
                getActivity().startService(asservice);
                getActivity().startService(notifyservice);
            } else {
                getActivity().stopService(service);
                getActivity().stopService(asservice);
                getActivity().stopService(notifyservice);
            }
        }

        private void FilterSet(final SharedPreferences setdata) {
            final ArrayList<String> FilterApplication = FormatArrayList.StringToStringArrayList(setdata.getString("Filter_Application", "[]"));
            getAppInfo(getActivity(), FilterApplication);
            AlertDialog.Builder alert = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.xml_global_win_filter)
                    .setMultiChoiceItems(AppNames, AppState, new DialogInterface.OnMultiChoiceClickListener() {
                        public void onClick(DialogInterface d, int i, boolean b) {
                            AppState[i] = b;
                        }
                    })
                    .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int i) {
                            FilterApplication.clear();
                            for (int a = 0; a < AppState.length; a++) {
                                if (AppState[a]) {
                                    FilterApplication.add(PkgNames[a]);
                                }
                            }
                            ((App) getActivity().getApplicationContext()).getFrameutil().setFilterApplication(FilterApplication);
                            SharedPreferences.Editor ed = setdata.edit();
                            ed.putString("Filter_Application", FilterApplication.toString());
                            ed.apply();
                        }
                    })
                    .setNegativeButton(R.string.cancel, null);
            alert.show();
        }

        private void LanguageSet(final Preference pre, final String[] lan_list) {
            AlertDialog.Builder lan = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.xml_global_language)
                    .setSingleChoiceItems(lan_list, language_choice, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            language_choice = which;
                        }
                    })
                    .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface p1, int p2) {
                            SharedPreferences setdata = getActivity().getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
                            setdata.edit().putInt("Language", language_choice).apply();
                            FloatManageMethod.LanguageSet(getActivity(), language_choice);
                            pre.setSummary(getString(R.string.xml_global_language_sum) + lan_list[language_choice]);
                            FloatManageMethod.restartApplication(getActivity(), getActivity().getPackageManager().getLaunchIntentForPackage(getActivity().getPackageName()));
                        }
                    })
                    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface d, int i) {
                            SharedPreferences setdata = getActivity().getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
                            language_choice = setdata.getInt("Language", 0);
                        }
                    });
            lan.show();
        }

        public void getTypeFace(final Preference pre) {
            File path = new File(Environment.getExternalStorageDirectory().toString() + "/FloatText/TTFs");
            if (!path.exists()) {
                //noinspection ResultOfMethodCallIgnored
                path.mkdirs();
            }
            File[] files = path.listFiles();
            int defaultchoice = 0;
            ArrayList<String> ttfs = new ArrayList<>();
            for (int i = 0; i < files.length; i++) {
                String str = files[i].getName();
                String extra = ActivityMethod.getExtraName(str);
                if (extra.equalsIgnoreCase("ttf")) {
                    String realname = str.substring(0, str.length() - 4);
                    ttfs.add(realname);
                    if (realname.equalsIgnoreCase(default_typeface)) {
                        defaultchoice = i + 1;
                    }
                }
            }
            typeface_choice = defaultchoice;
            ttfs.add(0, getString(R.string.text_default_typeface));
            final String[] ttfname = new String[ttfs.size()];
            for (int i = 0; i < ttfs.size(); i++) {
                ttfname[i] = ttfs.get(i);
            }
            AlertDialog.Builder pathselect = new AlertDialog.Builder(getActivity())
                    .setTitle(R.string.text_choose_typeface)
                    .setSingleChoiceItems(ttfname, defaultchoice, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface p1, int p2) {
                            typeface_choice = p2;
                        }
                    })
                    .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface p1, int p2) {
                            SharedPreferences setdata = getActivity().getSharedPreferences("ApplicationSettings", Activity.MODE_PRIVATE);
                            if (typeface_choice == 0) {
                                setdata.edit().putString("DefaultTTFName", "Default").apply();
                                pre.setSummary(getString(R.string.xml_global_text_typeface_summary) + getString(R.string.text_default_typeface));
                                default_typeface = "Default";
                            } else {
                                setdata.edit().putString("DefaultTTFName", ttfname[typeface_choice]).apply();
                                pre.setSummary(getString(R.string.xml_global_text_typeface_summary) + ttfname[typeface_choice]);
                                default_typeface = ttfname[typeface_choice];
                            }
                            FloatManageMethod.restartApplication(getActivity(), getActivity().getPackageManager().getLaunchIntentForPackage(getActivity().getPackageName()));
                        }
                    })
                    .setNegativeButton(R.string.cancel, null);
            pathselect.show();
        }

        public void setADTsum(Preference p) {
            Preference filter = findPreference("WinFilterSwitch");
            if (ActivityMethod.isAccessibilitySettingsOn(getActivity())) {
                filter.setEnabled(true);
                p.setSummary(getString(R.string.status) + getString(R.string.on) + "\n" + getString(R.string.xml_global_service_advancetext_sum));
            } else {
                filter.setEnabled(false);
                FloatManageMethod.setWinManager(getActivity());
                p.setSummary(getString(R.string.status) + getString(R.string.off) + "\n" + getString(R.string.xml_global_service_advancetext_sum));
            }
        }

        public void setNOSsum(Preference p) {
            if (ActivityMethod.isNotificationListenerEnabled(getActivity())) {
                p.setSummary(getString(R.string.status) + getString(R.string.on) + "\n" + getString(R.string.xml_global_service_notificationtext_sum));
            } else {
                p.setSummary(getString(R.string.status) + getString(R.string.off) + "\n" + getString(R.string.xml_global_service_notificationtext_sum));
            }
        }

        private void getAppInfo(Context ctx, ArrayList<String> PkgHave) {
            PackageManager pm = ctx.getPackageManager();
            List<PackageInfo> info = pm.getInstalledPackages(0);
            String FloatTextPkgName = ctx.getPackageName();
            ActivityMethod.orderPackageList(ctx, info);
            AppNames = new String[info.size() - 1];
            PkgNames = new String[info.size() - 1];
            AppState = new boolean[info.size() - 1];
            int countnum = 0;
            for (int i = 0; i < info.size(); i++) {
                String pkgname = info.get(i).packageName;
                if (!pkgname.equalsIgnoreCase(FloatTextPkgName)) {
                    AppNames[countnum] = info.get(i).applicationInfo.loadLabel(ctx.getPackageManager()).toString();
                    PkgNames[countnum] = pkgname;
                    AppState[countnum] = PkgHave.contains(pkgname);
                    countnum++;
                }
            }
        }
    }

} 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 FloatServiceMethod {

    //动态变量更新列表
    public static SharedPreferences setUpdateList(Context ctx) {
        SharedPreferences list = ctx.getSharedPreferences("DynamicList", Context.MODE_PRIVATE);
        SharedPreferences.Editor list_editor = list.edit();
        int version = list.getInt("Version", 0);
        if (version != StaticNum.DYNAMIC_LIST_VERSION) {
            ArrayList<String> KeyList = new ArrayList<>();
            ArrayList<Integer> InfoList = new ArrayList<>();
            KeyList.add("SystemTime");
            InfoList.add(0);
            KeyList.add("SystemTime_24");
            InfoList.add(0);
            KeyList.add("Clock");
            InfoList.add(0);
            KeyList.add("Clock_24");
            InfoList.add(0);
            KeyList.add("Date");
            InfoList.add(0);
            KeyList.add("CPURate");
            InfoList.add(0);
            KeyList.add("NetSpeed");
            InfoList.add(0);
            KeyList.add("MemRate");
            InfoList.add(0);
            KeyList.add("LocalIP");
            InfoList.add(0);
            KeyList.add("Battery");
            InfoList.add(0);
            KeyList.add("Sensor_Light");
            InfoList.add(0);
            KeyList.add("Sensor_Gravity");
            InfoList.add(0);
            KeyList.add("Sensor_Pressure");
            InfoList.add(0);
            KeyList.add("Sensor_CPUTemperature");
            InfoList.add(0);
            KeyList.add("Sensor_Proximity");
            InfoList.add(0);
            KeyList.add("Sensor_Step");
            InfoList.add(0);
            KeyList.add("ClipBoard");
            InfoList.add(0);
            KeyList.add("CurrentActivity");
            InfoList.add(0);
            KeyList.add("Notifications");
            InfoList.add(0);
            KeyList.add("Toasts");
            InfoList.add(0);
            KeyList.add("Week");
            InfoList.add(0);
            KeyList.add("(DateCount_)(.*?)");
            InfoList.add(1);
            KeyList.add("Second");
            InfoList.add(0);
            KeyList.add("Orientation");
            InfoList.add(0);
            KeyList.add("(DateUseCount_)(.*?)");
            InfoList.add(2);
            KeyList.add("NotificationPkg");
            InfoList.add(0);
            KeyList.add("WifiSignal");
            InfoList.add(0);
            list_editor.putInt("Version", StaticNum.DYNAMIC_LIST_VERSION);
            list_editor.putString("LIST", KeyList.toString());
            list_editor.putString("INFO", InfoList.toString());
            list_editor.apply();
        }
        return list;
    }

    //刷新动态变量状态
    public static void ReloadDynamicUse(Context ctx) {
        App utils = ((App) ctx.getApplicationContext());
        if (utils.DynamicNumService) {
            if (utils.getDynamicNumService()) {
                if (HasDynamicWord(ctx)) {
                    Intent intent = new Intent(ctx, FloatTextUpdateService.class);
                    intent.putExtra("RELOAD", true);
                    ctx.startService(intent);
                } else {
                    Intent intent = new Intent(ctx, FloatTextUpdateService.class);
                    ctx.stopService(intent);
                }
            }
        }
    }

    //确认是否存在动态变量
    private static boolean HasDynamicWord(Context ctx) {
        Pattern pat = Pattern.compile("<(.*?)>");
        Pattern pat2 = Pattern.compile("#(.*?)#");
        Pattern pat3 = Pattern.compile("\\[(.*?)\\]");
        ArrayList<String> list = ((App) ctx.getApplicationContext()).getFloatText();
        if (list.size() > 0) {
            String str = list.toString();
            str = str.substring(1, str.length() - 1).trim();
            Matcher mat = pat.matcher(str);
            Matcher mat2 = pat2.matcher(str);
            Matcher mat3 = pat3.matcher(str);
            if (mat.find() || mat2.find() || mat3.find()) {
                return true;
            }
        }
        return false;
    }

    //屏幕横竖判断
    public static String judgeOrientation(Context ctx) {
        int ori = ctx.getResources().getConfiguration().orientation;
        if (ori == Configuration.ORIENTATION_PORTRAIT) {
            return "PORTRAIT";
        } else if (ori == Configuration.ORIENTATION_LANDSCAPE) {
            return "LANDSCAPE";
        } else if (ori == Configuration.ORIENTATION_SQUARE) {
            return "SQUARE";
        }
        return "UNKNOWN";
    }

    //判断是否有字符
    public static boolean hasWord(String all, String[] part) {
        for (String str : part) {
            if (all.contains(str)) {
                return true;
            }
        }
        return false;
    }

    public static String[] StringtoStringArray(String str) {
        ArrayList<String> arr = FormatArrayList.StringToStringArrayList(str);
        return arr.toArray(new String[arr.size()]);
    }

    public static int[] StringtoIntegerArray(String str) {
        ArrayList<Integer> arr = FormatArrayList.StringToIntegerArrayList(str);
        return Itoi(arr.toArray(new Integer[arr.size()]));
    }

    //Integer值对象转换
    private static int[] Itoi(Integer[] B) {
        int[] b = new int[B.length];
        for (int i = 0; i < B.length; i++) {
            b[i] = B[i];
        }
        return b;
    }

    //修复null
    public static String fixnull(String str, String def) {
        if (str == null) {
            str = def;
        }
        return str;
    }

    //获取网速
    public static long getTotalRxBytes(Context ctx) {
        return TrafficStats.getUidRxBytes(ctx.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalRxBytes() / 1024);
    }

    public static long getTotalTxBytes(Context ctx) {
        return TrafficStats.getUidRxBytes(ctx.getApplicationInfo().uid) == TrafficStats.UNSUPPORTED ? 0 : (TrafficStats.getTotalTxBytes() / 1024);
    }

    //获取代理
    public static boolean isVpnUsed() {
        try {
            Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
            if (niList != null) {
                for (NetworkInterface intf : Collections.list(niList)) {
                    if (!intf.isUp() || intf.getInterfaceAddresses().size() == 0) {
                        continue;
                    }
                    if ("tun0".equals(intf.getName()) || "ppp0".equals(intf.getName())) {
                        return true;
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    //网速单位设置
    public static String netspeedset(float speed) {
        String NS = "KB/s";
        if (speed >= 1024) {
            NS = "MB/s";
            speed = speed / 1024;
            if (speed >= 1024) {
                NS = "GB/s";
                speed = speed / 1024;
            }
        }
        return new DecimalFormat("#0.00").format(speed * 100 / 100.00) + NS;
    }

    //获取CPU运行率
    public static int getProcessCpuRate() {
        int rate = 0;
        try {
            String Result;
            Process p = Runtime.getRuntime().exec("top -n 1 -m 1");
            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((Result = br.readLine()) != null) {
                if (Result.trim().length() >= 1) {
                    String[] CPUusr = Result.split("%");
                    String[] CPUusage = CPUusr[0].split("User");
                    String[] SYSusage = CPUusr[1].split("System");
                    rate = Integer.parseInt(CPUusage[1].trim()) + Integer.parseInt(SYSusage[1].trim());
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rate;
    }

    //获取内存状态
    public static String getMeminfo(Context ctx) {
        ActivityManager mam = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        mam.getMemoryInfo(mi);
        float total = mi.totalMem;
        float use = total - mi.availMem;
        return Math.round((double) (use / total) * 100) + "%";
    }

    //判断屏幕开启
    public static boolean isScreenOn(Context ctx) {
        PowerManager pm = (PowerManager) ctx.getSystemService(Context.POWER_SERVICE);
        return pm.isScreenOn();
    }

    //获取Wifi信号
    public static String getWifiSignal(Context ctx) {
        WifiManager wm = (WifiManager) ctx.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        return wm.getConnectionInfo().getRssi() + "db";
    }

    //获取IP
    public static String getIP(Context ctx) {
        WifiManager wifiService = (WifiManager) ctx.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiinfo = wifiService.getConnectionInfo();
        return intToIp(wifiinfo.getIpAddress());
    }

    //int转IP
    private static String intToIp(int i) {
        return (i & 0xFF) + "." + ((i >> 8) & 0xFF) + "." + ((i >> 16) & 0xFF) + "." + (i >> 24 & 0xFF);
    }

} 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;
} public class AdvanceRecyclerView extends RecyclerView {
    private View emptyView;

    final private AdapterDataObserver observer = new AdapterDataObserver() {
        @Override
        public void onChanged() {
            checkIfEmpty();
        }

        @Override
        public void onItemRangeInserted(int positionStart, int itemCount) {
            checkIfEmpty();
        }

        @Override
        public void onItemRangeRemoved(int positionStart, int itemCount) {
            checkIfEmpty();
        }
    };

    public AdvanceRecyclerView(Context context) {
        super(context);
    }

    public AdvanceRecyclerView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    public void setAdapter(Adapter adapter) {
        final Adapter oldAdapter = getAdapter();
        if (oldAdapter != null) {
            oldAdapter.unregisterAdapterDataObserver(observer);
        }
        super.setAdapter(adapter);
        if (adapter != null) {
            adapter.registerAdapterDataObserver(observer);
        }

        checkIfEmpty();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
        checkIfEmpty();
    }

    private void checkIfEmpty() {
        if (emptyView != null && getAdapter() != null) {
            final boolean emptyViewVisible = getAdapter().getItemCount() == 0;
            emptyView.setVisibility(emptyViewVisible ? VISIBLE : GONE);
            setVisibility(emptyViewVisible ? GONE : VISIBLE);
        }
    }
} public class ListViewAdapter extends RecyclerView.Adapter<ListViewAdapter.ViewHolder> {
    private final Context context;
    private final Activity activity;
    private ArrayList<String> textshow;
    private ArrayList<FloatTextView> floatdata;
    private ArrayList<WindowManager.LayoutParams> floatlayout;
    private Typeface typeface = null;

    public ListViewAdapter(Activity activity, ArrayList<String> textshow) {
        this.context = activity;
        this.activity = activity;
        this.textshow = textshow;
        String ttf = FloatTextSettingMethod.typeface_fix(context);
        if (ttf.equalsIgnoreCase("Default")) {
            typeface = null;
        } else {
            typeface = Typeface.createFromFile(ttf);
        }
    }

    //设置显示状态的数据
    public void setTextShow(ArrayList<String> ts) {
        this.textshow = ts;
    }

    @Override
    public int getItemCount() {
        return textshow.size();
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup p1, int p2) {
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.floatmanage_listview, p1, false);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final ViewHolder view, int p2) {
        final App utils = ((App) context.getApplicationContext());
        ArrayList<Boolean> Show = utils.getTextutil().getShowFloat();
        if (Show.size() != textshow.size()) {
            FloatManageMethod.restartApplication(context, context.getPackageManager().getLaunchIntentForPackage(context.getPackageName()));
        }
        String listtext = textshow.get(view.getLayoutPosition());
        //保持显示的文字和悬浮窗内样式一致
        TextReshow(view.getLayoutPosition(), utils, view, Show.get(view.getLayoutPosition()), listtext);
        //单行显示
        view.textView.setSingleLine(utils.ListTextHide);
        //锁定图标设置
        LockViewSet(view.getLayoutPosition(), view);
        //点击文字隐藏和显示悬浮窗
        view.textView.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FloatManageMethod.ShoworHideWin(context, view.getLayoutPosition());
            }
        });

        //锁定监听设置
        view.lock_button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                if (FloatManageMethod.LockorUnlockWin(context, view.getLayoutPosition())) {
                    FloatManage.snackshow((Activity) context, context.getString(R.string.text_lock));
                } else {
                    FloatManage.snackshow((Activity) context, context.getString(R.string.text_unlock));
                }
            }
        });
        //删除按钮监听
        view.del_button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                DelViewSet(view.getLayoutPosition());
            }
        });
        //编辑按钮监听
        view.edit_button.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                EditViewSet(view.getLayoutPosition());
            }
        });
    }

    private void TextReshow(int index, App utils, ViewHolder view, boolean show, String listtext) {
        FloatTextUtils textutils = utils.getTextutil();
        if (!show) {
            SpannableString str = new SpannableString(listtext);
            str.setSpan(new StrikethroughSpan(), 0, str.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            view.textView.setText(str);
        } else {
            view.textView.setText(listtext);
        }
        if (typeface != null) {
            view.textView.setTypeface(typeface);
        }
        if (textutils.getTextShadow().get(index)) {
            view.textView.setShadowLayer(textutils.getTextShadowRadius().get(index), textutils.getTextShadowX().get(index), textutils.getTextShadowY().get(index), textutils.getTextShadowColor().get(index));
        } else {
            view.textView.setShadowLayer(0, 0, 0, 0);
        }
        view.textView.getPaint().setFakeBoldText(utils.getTextutil().getThickShow().get(index));
        view.textView.setTextColor(utils.getTextutil().getColorShow().get(index));
        view.textView.setEllipsize(TextUtils.TruncateAt.END);
    }

    private void LockViewSet(int index, ViewHolder view) {
        ArrayList<Boolean> lock = ((App) context.getApplicationContext()).getTextutil().getLockPosition();
        if (lock.get(index)) {
            view.lock_button.setBackgroundResource(R.drawable.ic_lock);
        } else {
            view.lock_button.setBackgroundResource(R.drawable.ic_lock_unlocked);
        }
    }

    private void EditViewSet(int index) {
        App utils = ((App) context.getApplicationContext());
        floatdata = utils.getFrameutil().getFloatview();
        floatlayout = utils.getFrameutil().getFloatlayout();
        FloatWinEdit(activity, index);
        notifyItemChanged(index);
    }

    private void DelViewSet(final int index) {
        SharedPreferences spdata = PreferenceManager.getDefaultSharedPreferences(context);
        boolean show = spdata.getBoolean("FloatDeleteAlert", false);
        if (show) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(context)
                    .setTitle(R.string.ask_for_delete)
                    .setMessage(R.string.ask_for_delete_alert)
                    .setPositiveButton(R.string.done, new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface p1, int p2) {
                            delwin(index);
                        }
                    })
                    .setNegativeButton(R.string.cancel, null);
            dialog.show();
        } else {
            delwin(index);
        }
    }

    //控制删除悬浮窗的显示
    private void delwin(int index) {
        if (FloatWinDelete(index)) {
            FloatManage.snackshow((Activity) context, context.getString(R.string.delete_text_ok));
        } else {
            FloatManage.snackshow((Activity) context, context.getString(R.string.float_list_del_err));
        }
        FloatManageMethod.UpdateNotificationCount(context);
    }

    //删除悬浮窗
    private boolean FloatWinDelete(final int index) {
        App utils = ((App) context.getApplicationContext());
        FloatTextUtils textutils = utils.getTextutil();
        WindowManager wm = utils.getFloatwinmanager();
        floatdata = utils.getFrameutil().getFloatview();
        floatlayout = utils.getFrameutil().getFloatlayout();
        ArrayList<FloatLinearLayout> linearlayout = utils.getFrameutil().getFloatlinearlayout();
        ArrayList<Boolean> floatShow = textutils.getShowFloat();
        if (floatdata.size() - 1 < index || floatlayout.size() != linearlayout.size()) {
            return false;
        } else {
            if (floatShow.get(index)) {
                wm.removeView(linearlayout.get(index));
            }
            floatdata.remove(index);
            floatlayout.remove(index);
            linearlayout.remove(index);
            textshow.remove(index);
            textutils.removeDatas(index);
            utils.setTextutil(textutils);
            FloatIDChange(index);
            FloatData dat = new FloatData(context);
            dat.savedata();
            notifyItemRemoved(index);
            notifyItemRangeChanged(index, getItemCount());
            FloatServiceMethod.ReloadDynamicUse(context);
            return true;
        }
    }

    //改变悬浮窗内置序号(删除后调用)
    private void FloatIDChange(int delid) {
        App utils = (App) context.getApplicationContext();
        ArrayList<FloatLinearLayout> fll = utils.getFrameutil().getFloatlinearlayout();
        if (delid < fll.size()) {
            for (int i = delid; i < fll.size(); i++) {
                int id = fll.get(i).getFloatID();
                fll.get(i).setFloatID(id - 1);
            }
        }
    }

    private void FloatWinEdit(Activity act, int i) {
        Intent intent = new Intent(context, FloatTextSetting.class);
        intent.putExtra("EditMode", true);
        intent.putExtra("EditID", i);
        int FLOAT_RESULT_CODE = 0;
        act.startActivityForResult(intent, FLOAT_RESULT_CODE);
    }

    /*
     进入编辑窗口前需要保存数据
     */

    //控件获取
    static class ViewHolder extends RecyclerView.ViewHolder {
        final TextView textView;
        final Button del_button;
        final Button edit_button;
        final Button lock_button;

        ViewHolder(View view) {
            super(view);
            textView = (TextView) view.findViewById(R.id.textview_titleshow_floatmanage);
            del_button = (Button) view.findViewById(R.id.button_delete_floatmanage);
            edit_button = (Button) view.findViewById(R.id.button_edit_floatmanage);
            lock_button = (Button) view.findViewById(R.id.button_lock_floatmanage);
        }
    }

}
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import java.util.ArrayList;
import tool.xfy9326.floattext.Activity.AboutActivity;
import tool.xfy9326.floattext.Activity.GlobalSetActivity;
import tool.xfy9326.floattext.Method.FloatManageMethod;
import tool.xfy9326.floattext.Method.FloatServiceMethod;
import tool.xfy9326.floattext.Tool.FormatArrayList;
import tool.xfy9326.floattext.Utils.App;
import tool.xfy9326.floattext.Utils.FloatData;
import tool.xfy9326.floattext.Utils.StaticNum;
import tool.xfy9326.floattext.View.AdvanceRecyclerView;
import tool.xfy9326.floattext.View.ListViewAdapter;
package tool.xfy9326.floattext;




//悬浮窗后管理界面

public class FloatManage extends AppCompatActivity {
    private ListViewAdapter listadapter = null;
    private ArrayList<String> FloatDataName;
    private AlertDialog ag_loading;
    private Handler mHandler;

    //显示SnackBar
    public static void snackshow(Activity ctx, String str) {
        CoordinatorLayout cl = (CoordinatorLayout) ctx.findViewById(R.id.FloatManage_MainLayout);
        Snackbar sb = Snackbar.make(cl, str, Snackbar.LENGTH_SHORT);
        sb.show();
        System.gc();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        FloatManageMethod.RootTask(this);
        FloatManageMethod.LanguageInit(this);
        setContentView(R.layout.activity_float_manage);
        contentset();
        ag_loading = FloatManageMethod.setLoadingDialog(this);
        setHandle();
        SetAll(this);
    }

    //列表设置
    private void ListViewSet() {
        App utils = (App) getApplicationContext();
        FloatDataName = utils.getFloatText();
        listadapter = new ListViewAdapter(this, FloatDataName);
        AdvanceRecyclerView listview = (AdvanceRecyclerView) findViewById(R.id.listview_floatmanage);