Android 工具类

package com.xdtech.utils;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AppOpsManager;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Browser;
import android.provider.Settings;
import android.speech.tts.UtteranceProgressListener;
import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import com.google.android.material.tabs.TabLayout;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.core.app.NotificationManagerCompat;
import androidx.core.graphics.drawable.RoundedBitmapDrawable;
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory;
import androidx.viewpager.widget.ViewPager;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.customview.widget.ViewDragHelper;
import androidx.cardview.widget.CardView;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.style.ImageSpan;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyCharacterMap;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.BitmapImageViewTarget;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.xd.publicopinion.BuildConfig;
import com.xd.publicopinion.R;
import com.xdtech.app.YqtApplication;
import com.xdtech.constants.Flag;
import com.xdtech.dialog.CustomCameraDialog;
import com.xdtech.finger.BiometricPromptManager;
import com.xdtech.log.Logger;
import com.xdtech.manager.CommonManager;
import com.xdtech.manager.UserManager;
import com.xdtech.pojo.ComKeyword;
import com.xdtech.pojo.News;
import com.xdtech.pojo.OriginType;
import com.xdtech.pojo.SentiCondition;
import com.xdtech.pojo.SentiNewCondition;
import com.xdtech.pojo.UserSearchSet;
import com.xdtech.pojo.enums.AppVersionType;
import com.xdtech.pojo.event.EventMsg;
import com.xdtech.pojo.event.ObserverFlag;
import com.xdtech.push.YqtPushManager;
import com.xdtech.widget.RecyclerItemDecoration;
import com.xdtech.widget.lock.UnlockGesturePasswordActivity;
import com.xdtech.yq.adapter.CommonAdapter;
import com.xdtech.yq.adapter.NormalViewPagerAdapter;
import com.xdtech.yq.listener.CameraDialogChooseInterface;
import org.greenrobot.eventbus.EventBus;

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeoutException;
import java.util.regex.Pattern;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.content.Context.INPUT_METHOD_SERVICE;
import static android.text.TextUtils.isEmpty;
import static com.xdtech.pojo.enums.AppVersionType.CQYH;
import static com.xdtech.pojo.enums.AppVersionType.HBYQ;
import static com.xdtech.pojo.enums.AppVersionType.HNLT;
import static com.xdtech.pojo.enums.AppVersionType.MLQBT;
import static com.xdtech.pojo.enums.AppVersionType.YQGC;
import static com.xdtech.pojo.enums.AppVersionType.YQT;

public class Utils {
    static Map infoMap = new HashMap<>();
    /**
     * 收集错误处理信息
     *
     * @param context
     * @param e
     */
    public static void collectionDeviceInfo(Context context, Throwable e) {
        if(infoMap!=null){
            infoMap.clear();
        }
        //获得包管理器
        try {
            PackageManager pm = context.getPackageManager();
            //获取该应用信息
            PackageInfo pi = pm.getPackageInfo(context.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                StringWriter stringWriter = new StringWriter();
                PrintWriter printWriter = new PrintWriter(stringWriter);
                e.printStackTrace(printWriter);
                StringBuffer stringBuffer = stringWriter.getBuffer();
//                Log.i("CrashHandler", "stringBuffer.toString()="+stringBuffer.toString());

//                e.printStackTrace();
//                Log.i("CrashHandler", "stringBuffer.toString()="+ stringBuffer.toString()+"---end");
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                if(infoMap!=null){
                    infoMap.put("errorTime", Utils.getDateStringToLong(System.currentTimeMillis(),""));
                    infoMap.put("versionName", versionName);
                    infoMap.put("versionCode", versionCode);
                    infoMap.put("phone_brand", Build.BRAND);
                    infoMap.put("phone_version", Build.VERSION.RELEASE);
                    infoMap.put("phone_model", Build.MODEL);
                    infoMap.put("error", stringBuffer.toString());
                }
            }
        } catch (PackageManager.NameNotFoundException e1) {
            Log.i("CrashHandler", "获取信息失败");
            e1.printStackTrace();
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                if(infoMap!=null){
                    infoMap.put(field.getName(), field.get("").toString());
                }
            } catch (IllegalAccessException ex) {
                Log.i("CrashHandler", "try catch异常");
                ex.printStackTrace();
            }
        }
        Log.i("CrashHandler","infoMap.toString()="+infoMap.toString());
        //获取剪贴板管理器:
        ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
        // 创建普通字符型ClipData
        ClipData mClipData = ClipData.newPlainText("Label", infoMap.toString());
        // 将ClipData内容放到系统剪贴板里。
        cm.setPrimaryClip(mClipData);
    }
    public static void setSimple(TextView textView,boolean isSimpleType){
        if(isSimpleType){
            textView.setMaxLines(3);
            textView.setEllipsize(TextUtils.TruncateAt.END);
        }else{
            textView.setMaxLines(Integer.MAX_VALUE);
        }
    }
    public static boolean isNumber(String str){
        for (int i = 0; i < str.length(); i++){
            if (!Character.isDigit(str.charAt(i))){
                return false;
            }
        }
        return true;
    }
    @RequiresApi(api = Build.VERSION_CODES.N)
    public static String getStringTime(int dateType) {
        Calendar c = Calendar.getInstance(); // 当时的日期和时间
        int hour; // 需要更改的小时
        int day; // 需要更改的天数
        switch (dateType) {
            case 0: // 1小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - 1;
                c.set(Calendar.HOUR_OF_DAY, hour);
                break;
            case 1: // 2小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - 2;
                c.set(Calendar.HOUR_OF_DAY, hour);
                break;
            case 2: // 3小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - 3;
                c.set(Calendar.HOUR_OF_DAY, hour);
                break;
            case 3: // 6小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - 6;
                c.set(Calendar.HOUR_OF_DAY, hour);
                break;
            case 4: // 12小时前
                hour = c.get(Calendar.HOUR_OF_DAY) - 12;
                c.set(Calendar.HOUR_OF_DAY, hour);
                break;
            case 5: // 一天前
                day = c.get(Calendar.DAY_OF_MONTH) - 1;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 6: // 一星期前
                day = c.get(Calendar.DAY_OF_MONTH) - 7;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 7: // 一个月前
                day = c.get(Calendar.DAY_OF_MONTH) - 30;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 8: // 8天前
                day = c.get(Calendar.DAY_OF_MONTH) - 8;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 9: //3个月前
                day = c.get(Calendar.DAY_OF_MONTH) - 90;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 10: // 6个月前
                day = c.get(Calendar.DAY_OF_MONTH) - 180;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 11: // 12个月前
                day = c.get(Calendar.DAY_OF_MONTH) - 360;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 12: // 当时的日期和时间
                break;
            case 13: // 100天
                day = c.get(Calendar.DAY_OF_MONTH) - 100;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
            case 18: // 18个月前
                day = c.get(Calendar.DAY_OF_MONTH) - 540;
                c.set(Calendar.DAY_OF_MONTH, day);
                break;
        }
        android.icu.text.SimpleDateFormat sdf=new android.icu.text.SimpleDateFormat(date_format);
        //进行格式化
        return  sdf.format(c.getTime());
//        return c.getTimeInMillis();
    }
    public static String getSubstringEnd(String source,String a){
        if(!TextUtils.isEmpty(source)){
            if(source.endsWith(a)){
                int length=source.length();
                source=source.substring(0,length-1);
                return source;
            }else{
                return source;
            }
        }
        return "";
    }
    public static void setOriginTypeAndChildSelect(OriginType originType, boolean flag){
        if(originType!=null){
            if(originType.getLevel()==1){
                originType.setHasSelected(flag);
            }else {
                originType.setSelected(flag);
            }
            if(originType.getChildrenList()!=null && originType.getChildrenList().size()>0){
                for(OriginType childer : originType.getChildrenList()){
                    if(childer.getLevel()==1){
                        childer.setHasSelected(flag);
                    }else{
                        childer.setSelected(flag);
                    }
                    setOriginTypeAndChildSelect(childer,flag);
                }
            }
        }
    }
    public static Integer checkEmptyInt(Integer data){
        if(data==null){
            return 0;
        }else{
            return data;
        }
    }
    public static Boolean checkEmptyBoolean(Boolean data){
        if(data==null){
            return false;
        }else{
            return data;
        }
    }
    public static String checkEmpty(String data){
        if(TextUtils.isEmpty(data)){
            return "";
        }else {
            return data;
        }
    }
    public static String getEncode(String data){
        if(!TextUtils.isEmpty(data)){
            return URLEncoder.encode(data);
        }else {
            return "";
        }
    }
    /**
     * 获取错误的堆栈信息
     * @param throwable
     * @return
     */
    public static String getStackTrace(Throwable throwable){
        StringWriter stringWriter=new StringWriter();
        PrintWriter printWriter=new PrintWriter(stringWriter);
        try {
            throwable.printStackTrace(printWriter);
            return stringWriter.toString();
        }finally {
            printWriter.close();
        }
    }

    /**
     * 将异常信息转化成字符串
     * @param t
     * @return
     * @throws IOException
     */
    public static String exception(Throwable t) throws IOException{
        if(t == null)
            return null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try{
            t.printStackTrace(new PrintStream(baos));
        }finally{
            baos.close();
        }
        return baos.toString();
    }
    private String hanlderVoice(String voiceContent){
        if(!TextUtils.isEmpty(voiceContent)){
            if(voiceContent.length()>3000){
                return voiceContent.substring(0,3000);
            }else{
                return voiceContent;
            }
        }
        return "";
    }


    public static void showVoiceControl(String voiceContent, News news, CardView parent){
        YqtApplication.getInstance.setVoiceSurplusContent("");
        if(!TextUtils.isEmpty(voiceContent)){
            voiceContent = Html.fromHtml(voiceContent).toString();
            if(voiceContent.length()>3000){
                YqtApplication.getInstance.setVoiceSurplusContent(voiceContent.substring(3000,voiceContent.length()));
                voiceContent=voiceContent.substring(0,3000);
            }
        }

        if(!TextUtils.isEmpty(YqtApplication.getInstance.getVoiceIndexId())){
            if(news.getIndexId().equals(YqtApplication.getInstance.getVoiceIndexId())){
                if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                    YqtApplication.getInstance.setVoiceContent(voiceContent);
                } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                    voiceContent=YqtApplication.getInstance.getVoiceContent();
                } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                    voiceContent=YqtApplication.getInstance.getVoiceContent();
                }
            }else {
                if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                    YqtApplication.getInstance.setVoiceContent(voiceContent);
                } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                    YqtApplication.getInstance.setVoiceContent(voiceContent);
                } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                    YqtApplication.getInstance.setVoiceContent(voiceContent);
                }
            }
        }else{
            if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                YqtApplication.getInstance.setVoiceContent(voiceContent);
            } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                YqtApplication.getInstance.setVoiceContent(voiceContent);
            } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                YqtApplication.getInstance.setVoiceContent(voiceContent);
            }
        }
        voiceContent=YqtApplication.getInstance.getVoiceContent();
        if (!TextUtils.isEmpty(voiceContent) && news!=null) {
            List voiceList=new ArrayList<>();
            Logger.debug("voiceContent", "voiceContent.length()=" + voiceContent.length());
//            Utils.i("voiceContent", "voiceContent=" + voiceContent);
//            if(voiceContent.length()>=4000){
//                voiceContent=voiceContent.substring(0,3999);
//            }
//            String voiceContentZero="";
//            String voiceContentOne="";
//            String voiceContentTwo="";
//            final String[] voiceContentThree = {""};
//            int maxLong=3000;
//            if(voiceContent.length() < maxLong){
//                voiceList.add(voiceContent);
//            }else if(voiceContent.length() >= maxLong && voiceContent.length()< (maxLong*2) ){//6000
//                voiceContentZero=voiceContent.substring(0,maxLong);
//                voiceContent=voiceContentZero;
//                voiceContentOne=voiceContent.substring(maxLong,voiceContent.length());
//                voiceList.add(voiceContentZero);
//                voiceList.add(voiceContentOne);
//            }else if(voiceContent.length()>= (maxLong*2) && voiceContent.length()<(maxLong*3)){//6000--9000
//                voiceContentZero=voiceContent.substring(0,maxLong);
//                voiceContent=voiceContentZero;
//                voiceContentOne=voiceContent.substring(maxLong,maxLong*2);
//                voiceContentTwo=voiceContent.substring(maxLong*2,voiceContent.length());
//                voiceList.add(voiceContentZero);
//                voiceList.add(voiceContentOne);
//                voiceList.add(voiceContentTwo);
//            }else if(voiceContent.length()>= (maxLong*3) && voiceContent.length()<(maxLong*4)){
//                voiceContentZero=voiceContent.substring(0,maxLong);
//                voiceContent=voiceContentZero;
//                voiceContentOne=voiceContent.substring(maxLong,maxLong*2);
//                voiceContentTwo=voiceContent.substring(maxLong*2,maxLong*3);
//                voiceContentThree[0] =voiceContent.substring(maxLong*3,maxLong*4);
//            }else{
//                voiceContentZero=voiceContent.substring(0,maxLong);
//                voiceContent=voiceContentZero;
//                voiceContentOne=voiceContent.substring(maxLong,maxLong*2);
//                voiceContentTwo=voiceContent.substring(maxLong*2,maxLong*3);
//                voiceContentThree[0] =voiceContent.substring(maxLong*3,maxLong*4);
//            }

            //                chineseToSpeech.speech(voiceContent)
//            View voiceView=YqtApplication.getInstance.getVoiceView();
            View voiceView=null;
            if (voiceView != null) {
                parent.removeAllViews();
                parent.addView(voiceView);
                Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_closeVoice), "\ue6f5", R.color.color_999999, 22f);
                ImageView icon = voiceView.findViewById(R.id.icon);
                Utils.setDefHeadIcon(YqtApplication.getInstance, icon, news.getOriginType(), news.getProfileImageUrl());
            } else {
                voiceView = Utils.getLayoutView(YqtApplication.getInstance, R.layout.layout_float_window);
                parent.removeAllViews();
                parent.addView(voiceView);
            }
            if(voiceView!=null){
                Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_closeVoice), "\ue6f5", R.color.color_999999, 22f);
                ImageView icon = voiceView.findViewById(R.id.icon);
                Utils.setDefHeadIcon(YqtApplication.getInstance, icon, news.getOriginType(), news.getProfileImageUrl());
                String finalVoiceContent = voiceContent;
                View finalVoiceView = voiceView;
                voiceView.findViewById(R.id.tv_voiceControl).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                            YqtApplication.getInstance.setVoicePlayState(2);
                            YqtApplication.getInstance.setVoiceContent(finalVoiceContent);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, finalVoiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().speak(finalVoiceContent,news.getIndexId());
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                            YqtApplication.getInstance.setVoicePlayState(2);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, finalVoiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().resume();
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                            YqtApplication.getInstance.setVoicePlayState(1);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, finalVoiceView.findViewById(R.id.tv_voiceControl), "\ue6f6", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().pause();
                        }
                        EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
                    }
                });
                voiceView.findViewById(R.id.tv_closeVoice).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        YqtApplication.getInstance.setVoicePlayState(0);
                        YqtApplication.getInstance.getWhyTTS().pause();
                        parent.removeAllViews();
                        EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
                    }
                });
//                final String[] finalVoiceContentZero = {voiceContentZero};
//                final String[] finalVoiceContentOne = {voiceContentOne};
//                final String[] finalVoiceContentTwo = {voiceContentTwo};
                View finalVoiceView1 = voiceView;
                View finalVoiceView2 = voiceView;
                YqtApplication.getInstance.getWhyTTS().setOnUtteranceProgressListener(new UtteranceProgressListener() {
                    @Override
                    public void onStart(String utteranceId) {
//                        YqtApplication.getInstance.setVoicePlayState(1);
//                        Utils.setTypefaceTwo(YqtApplication.getInstance, view.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                    }

                    @Override
                    public void onDone(String utteranceId) {
                        Log.i("voiceContent","utteranceId="+utteranceId);
//                        if(!TextUtils.isEmpty(news.getVoiceContent())){
//                            if(news.getVoiceContent().length()>3000){
//                                String speakContent=news.getVoiceContent().substring(0,3000);
//                                YqtApplication.getInstance.getWhyTTS().speak(speakContent,news.getIndexId());
//                            }else{
//                                String speakContent=news.getVoiceContent().substring(0,news.getVoiceContent().length());
//                                YqtApplication.getInstance.getWhyTTS().speak(speakContent,news.getIndexId());
//                            }
//                        }else{
//
//                        }
                        YqtApplication.currentActivity.runOnUiThread(new Runnable() {
                            public void run() {
                                Logger.debug("voiceContent","------onDone");
//                                if(!TextUtils.isEmpty(finalVoiceContentZero[0])){
//                                    YqtApplication.getInstance.getWhyTTS().speak(finalVoiceContentZero[0],news.getIndexId());
//                                    finalVoiceContentZero[0] ="";
//                                }else if(!TextUtils.isEmpty(finalVoiceContentOne[0])){
//                                    YqtApplication.getInstance.getWhyTTS().speak(finalVoiceContentOne[0],news.getIndexId());
//                                    finalVoiceContentOne[0] ="";
//                                }else if(!TextUtils.isEmpty(finalVoiceContentTwo[0])){
//                                    YqtApplication.getInstance.getWhyTTS().speak(finalVoiceContentTwo[0],news.getIndexId());
//                                    finalVoiceContentTwo[0]="";
//                                }else if(!TextUtils.isEmpty(voiceContentThree[0])){
//                                    YqtApplication.getInstance.getWhyTTS().speak(voiceContentThree[0],news.getIndexId());
//                                    voiceContentThree[0] ="";
//                                } else{
                                if(!TextUtils.isEmpty(YqtApplication.getInstance.getVoiceSurplusContent())){
                                    if(YqtApplication.getInstance.getVoiceSurplusContent().length()>3000){
                                        YqtApplication.getInstance.setVoiceContent(YqtApplication.getInstance.getVoiceSurplusContent().substring(0,3000));
                                        YqtApplication.getInstance.setVoiceSurplusContent(YqtApplication.getInstance.getVoiceSurplusContent().substring(3000,YqtApplication.getInstance.getVoiceSurplusContent().length()));
                                        YqtApplication.getInstance.getWhyTTS().speak(YqtApplication.getInstance.getVoiceContent(),news.getIndexId());
                                    }else{
                                        YqtApplication.getInstance.getWhyTTS().speak(YqtApplication.getInstance.getVoiceSurplusContent(),news.getIndexId());
                                        YqtApplication.getInstance.setVoiceSurplusContent("");
                                    }
                                    YqtApplication.getInstance.setVoicePlayState(2);
                                    EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
                                }else{
                                    YqtApplication.getInstance.setVoicePlayState(0);
                                    EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
                                    Utils.setTypefaceTwo(YqtApplication.getInstance, finalVoiceView1.findViewById(R.id.tv_voiceControl), "\ue6f6", R.color.color_999999, 22f);
                                }

//                                }
                            }
                        });

                    }

                    @Override
                    public void onError(String utteranceId) {
                        YqtApplication.currentActivity.runOnUiThread(new Runnable() {
                            public void run() {
                                YqtApplication.getInstance.setVoicePlayState(0);
                                EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
                                Utils.setTypefaceTwo(YqtApplication.getInstance, finalVoiceView2.findViewById(R.id.tv_voiceControl), "\ue6f6", R.color.color_999999, 22f);
                            }
                        });
                    }
                });
                if(!TextUtils.isEmpty(YqtApplication.getInstance.getVoiceIndexId())){
                    if(news.getIndexId().equals(YqtApplication.getInstance.getVoiceIndexId())){
                        if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                            YqtApplication.getInstance.setVoicePlayState(2);
                            YqtApplication.getInstance.setVoiceContent(voiceContent);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().speak(voiceContent,news.getIndexId());
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                            YqtApplication.getInstance.setVoicePlayState(2);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().resume();
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                            YqtApplication.getInstance.setVoicePlayState(1);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f6", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().pause();
                        }
                    }else {
                        if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                            YqtApplication.getInstance.setVoicePlayState(2);
                            YqtApplication.getInstance.setVoiceContent(voiceContent);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().speak(voiceContent,news.getIndexId());
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                            YqtApplication.getInstance.setVoicePlayState(2);
                            YqtApplication.getInstance.setVoiceContent(voiceContent);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().speak(voiceContent,news.getIndexId());
                        } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                            YqtApplication.getInstance.setVoicePlayState(2);
                            YqtApplication.getInstance.setVoiceContent(voiceContent);
                            Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                            YqtApplication.getInstance.getWhyTTS().speak(voiceContent,news.getIndexId());
                        }
                    }
                }else{
                    if (YqtApplication.getInstance.getVoicePlayState() == 0) {//停止
                        YqtApplication.getInstance.setVoicePlayState(2);
                        YqtApplication.getInstance.setVoiceContent(voiceContent);
                        Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                        YqtApplication.getInstance.getWhyTTS().speak(voiceContent,news.getIndexId());
                    } else if (YqtApplication.getInstance.getVoicePlayState() == 1) {//暂停
                        YqtApplication.getInstance.setVoicePlayState(2);
                        Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f7", R.color.color_999999, 22f);
                        YqtApplication.getInstance.getWhyTTS().resume();
                    } else if (YqtApplication.getInstance.getVoicePlayState() == 2) {//播放状态
                        YqtApplication.getInstance.setVoicePlayState(1);
                        Utils.setTypefaceTwo(YqtApplication.getInstance, voiceView.findViewById(R.id.tv_voiceControl), "\ue6f6", R.color.color_999999, 22f);
                        YqtApplication.getInstance.getWhyTTS().pause();
                    }
                }
                YqtApplication.getInstance.setVoiceIndexId(news.getIndexId());
                EventBus.getDefault().post(new EventMsg(ObserverFlag.voice_play_state,YqtApplication.getInstance.getVoicePlayState(),""));
            }
        }
    }
    public static void setHUAWEIIconBadgeNum(Context context,int count) {
        if(Utils.isHuawei()){
            Bundle bunlde = new Bundle();
            bunlde.putString("package", context.getPackageName());
            bunlde.putString("class", "com.xdtech.yq.activity.SplashActivity");
            bunlde.putInt("badgenumber", count);
            context.getContentResolver().call(Uri.parse("content://com.huawei.android.launcher.settings/badge/"), "change_badge", null, bunlde);
        }
    }
    public static RequestBody toRequestBodyOfText (String value) {
        RequestBody body = RequestBody.create(MediaType.parse("text/plain"), value);
        return body ;
    }

    public static RequestBody toRequestBodyOfImage(File pFile){
        RequestBody fileBody = RequestBody.create(MediaType.parse("image/*"), pFile);
        return fileBody;
    }
    public static void setMargins (View view, int left, int top, int right, int bottom) {
        if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
            p.setMargins(left, top, right, bottom);
            view.requestLayout();
        }
    }
    /**
     * 解决在页面底部置输入框,输入法弹出遮挡部分输入框的问题
     * @param root 页面根元素
     *
     */
    public static void controlKeyboardLayout(final View root,
                                             final View editLayout) {
        // TODO Auto-generated method stub
        root.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                // TODO Auto-generated method stub
                Rect rect=new Rect();
                //获取root在窗体的可视区域
                root.getWindowVisibleDisplayFrame(rect);
                //获取root在窗体的不可视区域高度(被其他View遮挡的区域高度)
                int rootInVisibleHeigh = root.getRootView().getHeight()-rect.bottom;
                //若不可视区域高度大于100,则键盘显示
                if (rootInVisibleHeigh > 100) {
                    Log.v("hjb", "不可视区域高度大于100,则键盘显示");
                    int[] location = new int[2];
                    //获取editLayout在窗体的坐标
                    editLayout.getLocationInWindow(location);
                    //计算root滚动高度,使editLayout在可见区域
                    int srollHeight = (location[1] + editLayout.getHeight()) - rect.bottom;
                    root.scrollTo(0, srollHeight);
                } else {
                    //键盘隐藏
                    Log.v("hjb", "不可视区域高度小于100,则键盘隐藏");
                    root.scrollTo(0, 0);
                }
            }
        });
    }

    /**
     * 获取应用程序名称
     */
    public static synchronized String getAppName(Context context) {
        try {
            PackageManager packageManager = context.getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(
                    context.getPackageName(), 0);
            int labelRes = packageInfo.applicationInfo.labelRes;
            return context.getResources().getString(labelRes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**

     * [获取应用程序版本名称信息]

     * @param context

     * @return 当前应用的版本名称

     */

    public static synchronized String getPackageName(Context context) {
        try {

            PackageManager packageManager = context.getPackageManager();

            PackageInfo packageInfo = packageManager.getPackageInfo(

                    context.getPackageName(), 0);

            return packageInfo.packageName;

        } catch (Exception e) {

            e.printStackTrace();

        }

        return "";

    }
    public static Bitmap getBitmapByUrl(String url) {
        Bitmap bm = null;
        try {
            URL iconUrl = new URL(url);
            URLConnection conn = iconUrl.openConnection();
            HttpURLConnection http = (HttpURLConnection) conn;

            int length = http.getContentLength();

            conn.connect();
            // 获得图像的字符流
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is, length);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();// 关闭流
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        return bm;
    }
    /**
     * 把bitmap画到一个白底的newBitmap上,将newBitmap返回
     * @param context 上下文
     * @param bitmap 要绘制的位图
     * @return Bitmap
     */
    public static Bitmap drawableBitmapOnWhiteBg(Context context,Bitmap bitmap){
        Bitmap newBitmap = Bitmap.createBitmap(200, 200, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(newBitmap);
        canvas.drawColor(context.getResources().getColor(android.R.color.white));
        Paint paint=new Paint();
        canvas.drawBitmap(bitmap, 0, 0, paint); //将原图使用给定的画笔画到画布上
        return newBitmap;
    }
    public static void handleNetError(Throwable e){
        if (e instanceof ConnectException || e instanceof UnknownHostException) {
            ToastUtils.showText("网络异常,请检查网络");
        } else if (e instanceof TimeoutException || e instanceof SocketTimeoutException) {
            ToastUtils.showText("网络不畅,请稍后再试!");
        } else if (e instanceof JsonSyntaxException) {
            ToastUtils.showText("数据解析异常");
        } else {
            ToastUtils.showText("服务端错误");
        }
    }
    public static String getUTFEncoder(String resString) {
        if(!TextUtils.isEmpty(resString)){
            String strUTF8 = null;
            //URLEncoder.encode()
            try {
                strUTF8 = URLDecoder.decode(resString, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return strUTF8;
        }else{
            return "";
        }
    }
    public static String dealPercent(String resString){
        if(!TextUtils.isEmpty(resString)){
            String newString = resString.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            return newString;
        }
        return "";
    }
    public static boolean isHasReply(){
        if(!TextUtils.isEmpty(YqtApplication.getInstance.getAppColumnOrder())){
            String [] orderArr=YqtApplication.getInstance.getAppColumnOrder().split(",");
            for(int i=0;i pinfo = packageManager.getInstalledPackages(0);
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                //通过遍历应用所有包名进行判断
                if (pn.equals("com.tencent.mobileqq")) {
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * bitmap转为base64
     *
     * @param bitmap
     * @return
     */
    public static String bitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.DEFAULT);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
    /**
     * 判断手机通知是否开启,没有开启则打开应用管理权限页面
     * @param context
     */
    public static void showDelDialog(final Context context){
        // 构造对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);//构建一个AlertDialog.Builder对象
        builder.setTitle("温馨提示");//设置标题
        //        builder.setIcon(R.drawable.ic_app);//设置图标
        builder.setMessage("你推送功能尚未开启,会影响您的正常使用,请开启推送功能");//设置提示内容
        //创建两个点击事件
        // 更新
        builder.setPositiveButton("确认打开", new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface dialog, int which) {
                //根据包名打开对应的应用权限设置页面
                dialog.dismiss();
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);//设置去向意图
                Uri uri = Uri.fromParts("package", context.getPackageName(), null);
                intent.setData(uri);
                //发起跳转
                context.startActivity(intent);
            }
        });
        // 稍后更新
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //关闭对话框
                dialog.dismiss();
            }
        });
        Dialog noticeDialog = builder.create();
        noticeDialog.setCanceledOnTouchOutside(false);
        noticeDialog.setCancelable(false);
        noticeDialog.show();
    }
    /**
     * 判断该应用通知开关是否开启
     * @param context
     * @return
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)//提高 Android 高版本的兼容
    public static boolean isNotificationEnabled(Context context) {
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
            NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
            boolean areNotificationsEnabled = notificationManagerCompat.areNotificationsEnabled();
            return areNotificationsEnabled;
        }
        String CHECK_OP_NO_THROW = "checkOpNoThrow";
        String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION";
        AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE);
        ApplicationInfo appInfo = context.getApplicationInfo();
        String pkg = context.getApplicationContext().getPackageName();//获取该应用信息
        int uid = appInfo.uid;

        Class appOpsClass = null;
        try {
            appOpsClass = Class.forName(AppOpsManager.class.getName());
            Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE,
                    String.class);
            Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION);

            int value = (Integer) opPostNotificationValue.get(Integer.class);
            //根据信息得到值进行比较 如果相等则返回true 否则返回false
      return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return false;
    }
    public static void openPDFInBrowser(Context context, String url) {
        Uri uri = Uri.parse(url);
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.putExtra(Browser.EXTRA_APPLICATION_ID, context.getPackageName());
        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            Log.w("error", "Activity was not found for intent, " + intent.toString());
        }
    }
    /**
     * glide加载头像(圆形)
     * @param activity
     * @param url
     * @param imageView
     * @param default_image
     */
    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static void glideAvatarLoad(final Activity activity, String url, final ImageView imageView, int default_image) {
        if (!activity.isDestroyed()) {
            Glide.with(activity).load(url).asBitmap().placeholder(default_image).error(default_image).centerCrop().into(new BitmapImageViewTarget(imageView){
                @Override
                protected void setResource(Bitmap resource) {
                    RoundedBitmapDrawable circularBitmapDrawable =
                            RoundedBitmapDrawableFactory.create(activity.getResources(), resource);
                    circularBitmapDrawable.setCircular(true);
                    imageView.setImageDrawable(circularBitmapDrawable);
                }
            });
        }
    }
    public static boolean existSDCard() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        } else
            return false;
    }
    /**
     * 显示选择相机dialog
     * @param context
     * @param chooseInterface
     */
    public static CustomCameraDialog  showCameraDialog(Context context,  final CameraDialogChooseInterface chooseInterface){
        final CustomCameraDialog dialog;
        CustomCameraDialog.Builder builder = new CustomCameraDialog.Builder(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.layout_camera_choose, null);
        TextView camera_type = (TextView) view.findViewById(R.id.camera_type);
        TextView tv_system_camera = (TextView) view.findViewById(R.id.tv_system_camera);
        TextView camera_cancle = (TextView) view.findViewById(R.id.camera_cancle);

        builder.setContentView(view)
                .setCanceledOnTouchOutside(true)
                .setGravity(Gravity.BOTTOM)
                .setMargin(0);
        dialog = builder.create();
        camera_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseInterface.onCameraChoose(0);
                if(dialog !=null){
                    dialog.dismiss();
                }
            }
        });
        tv_system_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseInterface.onCameraChoose(1);
                if(dialog !=null){
                    dialog.dismiss();
                }
            }
        });
        camera_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(dialog !=null){
                    dialog.dismiss();
                }

            }
        });
        dialog.show();
        return dialog;
    }
    /**
     * 显示选择相机dialog
     * @param context
     * @param chooseInterface
     */
    static boolean  sendCancel=true;
    public static CustomCameraDialog  showCameraWebViewDialog(Context context,  final CameraDialogChooseInterface chooseInterface){
        sendCancel=true;
        final CustomCameraDialog dialog;
        CustomCameraDialog.Builder builder = new CustomCameraDialog.Builder(context);
        LayoutInflater inflater = LayoutInflater.from(context);
        View view = inflater.inflate(R.layout.layout_camera_choose, null);
        TextView camera_type = (TextView) view.findViewById(R.id.camera_type);
        TextView tv_system_camera = (TextView) view.findViewById(R.id.tv_system_camera);
        TextView camera_cancle = (TextView) view.findViewById(R.id.camera_cancle);

        builder.setContentView(view)
                .setCanceledOnTouchOutside(true)
                .setGravity(Gravity.BOTTOM)
                .setMargin(0);
        dialog = builder.create();
        camera_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCancel=false;
                chooseInterface.onCameraChoose(0);
                if(dialog !=null){
                    dialog.dismiss();
                }
            }
        });
        tv_system_camera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCancel=false;
                chooseInterface.onCameraChoose(1);
                if(dialog !=null){
                    dialog.dismiss();
                }
            }
        });
        camera_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendCancel=true;
                if(dialog !=null){
                    dialog.dismiss();
                }

            }
        });
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if(sendCancel){
                    EventBus.getDefault().post(new EventMsg(ObserverFlag.webview_init_upload_image));
                }
            }
        });
        dialog.show();
        return dialog;
    }
    public static void  fingerAuth(Activity context){
        BiometricPromptManager mManager = BiometricPromptManager.from(context);
        if (mManager.isBiometricPromptEnable() && UserManager.getLock(UserManager.getEncode()).equals("1")) {
            mManager.authenticate(new BiometricPromptManager.OnBiometricIdentifyCallback() {
                @Override
                public void onUsePassword() {
//                    Toast.makeText(context, "onUsePassword", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onSucceeded() {
                    EventBus.getDefault().post(new EventMsg(ObserverFlag.finger_verify_success));
                    Toast.makeText(context, "指纹验证成功", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailed() {
                    Toast.makeText(context, "指纹验证失败", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(int code, String reason) {
                    Toast.makeText(context, "指纹验证出错", Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onCancel() {
                    Toast.makeText(context, "onCancel", Toast.LENGTH_SHORT).show();
                }
            });
        }else{
            if(CommonManager.isGestureOpen()){
                Intent intent=new Intent(context,UnlockGesturePasswordActivity.class);
                context.startActivity(intent);
            }
        }
    }
    public static  T notEmpty(final T argument, final String name) {
        if (argument == null) {
            throw new IllegalArgumentException(name + " may not be null");
        }
        if (TextUtils.isEmpty(argument)) {
            throw new IllegalArgumentException(name + " may not be empty");
        }
        return argument;
    }
    public static  T notNull(final T argument, final String name) {
        if (argument == null) {
            throw new IllegalArgumentException(name + " may not be null");
        }
        return argument;
    }
    public static byte[] getBytes(final String data, final String charset) {
        notNull(data, "Input");
        notEmpty(charset, "Charset");
        try {
            return data.getBytes(charset);
        } catch (final UnsupportedEncodingException e) {
            return data.getBytes();
        }
    }
    /*
     * deviceID的组成为:渠道标志+识别符来源标志+hash后的终端识别符
     *
     * 渠道标志为:
     * 1,andriod(a)
     *
     * 识别符来源标志:
     * 1, wifi mac地址(wifi);
     * 2, IMEI(imei);
     * 3, 序列号(sn);
     * 4, id:随机码。若前面的都取不到时,则随机生成一个随机码,需要缓存。
     *
     * @param context
     * @return
     */
//    public static String getDeviceId(Context context) {
//        StringBuilder deviceId = new StringBuilder();
//        // 渠道标志
//        deviceId.append("a");
//        try {
//            //wifi mac地址
//            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//            WifiInfo info = wifi.getConnectionInfo();
//            String wifiMac = info.getMacAddress();
//            if(!isEmpty(wifiMac)){
//                deviceId.append("wifi");
//                deviceId.append(wifiMac);
//                return deviceId.toString();
//            }
//            //IMEI(imei)
//            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
//            @SuppressLint("MissingPermission") String imei = tm.getDeviceId();
//            if(!isEmpty(imei)){
//                deviceId.append("imei");
//                deviceId.append(imei);
//                return deviceId.toString();
//            }
//            //序列号(sn)
//            @SuppressLint("MissingPermission") String sn = tm.getSimSerialNumber();
//            if(!isEmpty(sn)){
//                deviceId.append("sn");
//                deviceId.append(sn);
//                return deviceId.toString();
//            }
//            //如果上面都没有, 则生成一个id:随机码
//            String uuid = getUUID(context);
//            if(!isEmpty(uuid)){
//                deviceId.append("id");
//                deviceId.append(uuid);
//                return deviceId.toString();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            deviceId.append("id").append(getUUID(context));
//        }
//        return deviceId.toString();
//    }
    /**
     * 得到全局唯一UUID
     */
    public static String getUUID(){
        String uuid = UserManager.getUUID();
        if(TextUtils.isEmpty(uuid)){
            uuid = UUID.randomUUID().toString();
            UserManager.setUUID(uuid);
        }
        return uuid;
    }

    public static byte[] stringToBytes(String str) {
        try {
            // 使用指定的字符集将此字符串编码为byte序列并存到一个byte数组中
            return str.getBytes("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getSerialId(){
         String s= "serial_id_"+BuildConfig.appFlag;
         Log.i("Serial","serial_id_string="+s);
        return s;
    }
//    public static void getShowDatePickDialog(Context context, DateType type, final TextView textView, final PickDialogListener listener) {
//        final DatePickDialog dialog = new DatePickDialog(context);
//        java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat(Flag.time_format);//小写的mm表示的是分钟
//        String start_date=textView.getText().toString();
//        Log.i("Dialog","start_date="+start_date);
//        Date date= null;
//        try {
//            date = sdf.parse(start_date);
//        } catch (java.text.ParseException e) {
//            //e.printStackTrace();
//            date=new Date();
//        }
//        dialog.setStartDate(date);
//        //设置上下年分限制
//        dialog.setYearLimt(5);
//        //设置标题
//        dialog.setTitle("选择时间");
//        //设置类型
//        dialog.setType(type);
//        //设置消息体的显示格式,日期格式
//        dialog.setMessageFormat(Flag.time_format);
//        //设置选择回调
//        dialog.setOnChangeLisener(new OnChangeLisener() {
//            @Override
//            public void onChanged(Date date) {
//
//            }
//        });
//        //设置点击确定按钮回调
//        dialog.setOnSureLisener(new OnSureLisener() {
//            @RequiresApi(api = Build.VERSION_CODES.N)
//            @Override
//            public void onSure(Date date) {
//                java.util.Calendar ca = java.util.Calendar.getInstance();//得到一个Calendar的实例
//                ca.setTime(new Date()); //设置时间为当前时间
//                ca.add(java.util.Calendar.YEAR, -1); //年份减1
//                Long old_time=ca.getTime().getTime();
                Long old_time= null;
                try {
                    old_time = MyDateUtils.getAnyOneDayTime("2018-01-01");
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                if(date.getTime()>System.currentTimeMillis()){//更新时间大于当前时间
                    date=new Date(System.currentTimeMillis());
                    java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat(Flag.time_format);
                    String str=sdf.format(date);
                    textView.setText(str);
                }else
                    if(old_time>date.getTime()){//如果选择时间小于最小时间
                    java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat(Flag.time_format);
                    String str=sdf.format(old_time);
                    textView.setText(str);
                }else {
//                java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat(Flag.time_format);
//                String str=sdf.format(date);
//                textView.setText(str);
                }
//                if(listener!=null){
//                    listener.onPickDialogSure();
//                }
//                if(dialog!=null){
//                    dialog.dismiss();
//                }
//            }
//        });
//        dialog.show();
//    }
    public static String getDateFormat(String sourceDate,String sourceFormat,String resultFormat){
        return Utils.getDateStringToLong(Utils.getDateStringToLong(sourceDate,"yyyy-MM-dd HH:mm:ss"),"MM-dd HH:mm");
    }
    public static String getDateStringToLong(Long mill, String format){
        //mill为你龙类型的时间戳
        if(mill!=null){
            Date date=new Date(mill);
            String strs="";
            try {
                //yyyy表示年MM表示月dd表示日
                //yyyy-MM-dd是日期的格式,比如2015-12-12如果你要得到2015年12月12日就换成yyyy年MM月dd日
                if(isEmpty(format)){
                    format=date_format;
                }
                SimpleDateFormat sdf=new SimpleDateFormat(format);
                //进行格式化
                strs=sdf.format(date);
                return strs;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }
    public static final String date_format="yyyy-MM-dd HH:mm:ss";
    public static long getDateStringToLong(String strTime, String formatType)
            throws ParseException {
        if(isEmpty(formatType)){
            formatType=date_format;
        }
        Date date = stringToDate(strTime, formatType); // String类型转成date类型
        if (date == null) {
            return 0;
        } else {
            long currentTime = date.getTime(); // date类型转成long类型
            return currentTime;
        }
    }
    public static Date stringToDate(String strTime, String formatType)
    {
        SimpleDateFormat formatter = new SimpleDateFormat(formatType);
        Date date = null;
        try {
            date = formatter.parse(strTime);
        } catch (java.text.ParseException e) {
            e.printStackTrace();
        }
        return date;
    }
    public static void setEditTextTop(FragmentActivity context,View contentView){
        View decorView = context.getWindow().getDecorView();
//        View contentView = context.findViewById(Window.ID_ANDROID_CONTENT);
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);
                int height = decorView.getRootView().getHeight();
                int diff = height - r.bottom;
                if (diff != 0) {
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        });
    }
    public static void setEditTextTop(FragmentActivity context){
        View decorView = context.getWindow().getDecorView();
        View contentView = context.findViewById(Window.ID_ANDROID_CONTENT);
        contentView.setBackgroundColor(context.getResources().getColor(R.color.color_background));
        decorView.getViewTreeObserver().addOnGlobalLayoutListener(getGlobalLayoutListener(context,decorView, contentView));
    }
    private static ViewTreeObserver.OnGlobalLayoutListener getGlobalLayoutListener(FragmentActivity context,final View decorView, final View contentView) {
        return new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                Rect r = new Rect();
                decorView.getWindowVisibleDisplayFrame(r);
                int height = decorView.getRootView().getHeight();
                int diff = height - r.bottom;
                if (diff != 0) {
//                    if(isNavigationBarShow(context)){
//                        diff=diff-getActionBarHeight(context);
//                    }
                    contentView.setBackgroundColor(context.getResources().getColor(R.color.color_background));
                    if (contentView.getPaddingBottom() != diff) {
                        contentView.setPadding(0, 0, 0, diff);
                    }
                } else {
                    contentView.setBackgroundColor(context.getResources().getColor(R.color.color_00000000));
                    if (contentView.getPaddingBottom() != 0) {
                        contentView.setPadding(0, 0, 0, 0);
                    }
                }
            }
        };
    }
    public static boolean isNavigationBarShow(Activity context){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            Display display = context.getWindowManager().getDefaultDisplay();
            Point size = new Point();
            Point realSize = new Point();
            display.getSize(size);
            display.getRealSize(realSize);
            boolean  result  = realSize.y!=size.y;
            return realSize.y!=size.y;
        }else {
            boolean menu = ViewConfiguration.get(context).hasPermanentMenuKey();
            boolean back = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
            if(menu || back) {
                return false;
            }else {
                return true;
            }
        }
    }
//    /**
//     * 获取是否存在NavigationBar,是否有虚拟按钮
//     */
//    public static boolean checkDeviceHasNavigationBar(Context context) {
//        boolean hasNavigationBar = false;
//        Resources rs = context.getResources();
//        int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
//        if (id > 0) {
//            hasNavigationBar = rs.getBoolean(id);
//        }
//        try {
//            Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
//            Method m = systemPropertiesClass.getMethod("get", String.class);
//            String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
//            if ("1".equals(navBarOverride)) {
//                hasNavigationBar = false;
//            } else if ("0".equals(navBarOverride)) {
//                hasNavigationBar = true;
//            }
//        } catch (Exception e) {
//
//        }
//        return hasNavigationBar;
//
//    }
    /**
     * 获取虚拟按钮ActionBar的高度
     *
     * @param activity activity
     * @return ActionBar高度
     */
    public static int getActionBarHeight(Context activity) {
        TypedValue tv = new TypedValue();
        if (activity.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
            return TypedValue.complexToDimensionPixelSize(tv.data, activity.getResources().getDisplayMetrics());
        }
        return 0;
    }
    /**
     * 获取导航栏高度(如华为底部导航栏高度)
     *
     * @param context
     * @return
     */
    public static int getBottomBarHeight(Context context) {
        int resourceId = 0;
        int rid = context.getResources().getIdentifier("config_showNavigationBar", "bool", "android");
        if (rid != 0) {
            resourceId = context.getResources().getIdentifier("navigation_bar_height", "dimen", "android");
            return context.getResources().getDimensionPixelSize(resourceId);
        } else
            return 0;
    }
    public static void openSoftInputFromWindow(FragmentActivity context,EditText editText) {
        editText.requestFocus();
        context.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    }
    static PopupWindow popWindow;
    public static PopupWindow showPopWindow(FragmentActivity context,View view,View contentView) {
        popWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT, true);
        WindowManager.LayoutParams params = context.getWindow().getAttributes();
        params.alpha = 0.5f;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setBackgroundDrawable(new ColorDrawable(0xffffffff));
        context.getWindow().setAttributes(params);
        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
        popWindow.setOutsideTouchable(true);
        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = context.getWindow().getAttributes();
                params.alpha = 1f;
                context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                context.getWindow().setAttributes(params);
            }
        });
        popWindow.showAsDropDown(view);
        return popWindow;
    }
//    public static PopupWindow showPopWindow(FragmentActivity context,View view,View contentView) {
//        if (popWindow != null && imms != null) {
//            imms.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//        }
//        imms = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
//        popWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT,
//                ViewGroup.LayoutParams.WRAP_CONTENT, true);
//        WindowManager.LayoutParams params = context.getWindow().getAttributes();
//        params.alpha = 0.5f;
//        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//        context.getWindow().setAttributes(params);
//        popWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
//        imms.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);
//        popWindow.setBackgroundDrawable(new ColorDrawable(0x00000000));
//        popWindow.setOutsideTouchable(true);
//        popWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
//            @Override
//            public void onDismiss() {
//                WindowManager.LayoutParams params = context.getWindow().getAttributes();
//                params.alpha = 1f;
//                context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
//                context.getWindow().setAttributes(params);
//            }
//        });
//        popWindow.showAsDropDown(view);
//        return popWindow;
//    }
    public static void colseSoftInput(FragmentActivity context){
        if(context.getCurrentFocus()!=null){
            ((InputMethodManager)context.getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }
    public static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }
    /**
     * 设置viewPager和tabLayout
     * @param context
     * @param viewPager
     * @param tableLayout
     */
    public static void setViewPagerTableLayout(FragmentActivity context, ViewPager viewPager, TabLayout tableLayout,
                                               ArrayList arrayList, ArrayList stringList){
        NormalViewPagerAdapter adapter=new NormalViewPagerAdapter(context.getSupportFragmentManager());
        adapter.setFragmentList(arrayList);
        adapter.setTitleList(stringList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(2);
        tableLayout.setupWithViewPager(viewPager);
        tableLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    public static void setDrawerLeftEdgeSize(Activity activity, DrawerLayout drawerLayout, float displayWidthPercentage) {
        if (activity == null || drawerLayout == null) return;
        try {
            Field leftDraggerField = drawerLayout.getClass().getDeclaredField("mLeftDragger");
            leftDraggerField.setAccessible(true);
            ViewDragHelper leftDragger = (ViewDragHelper) leftDraggerField.get(drawerLayout);
            Field edgeSizeField = leftDragger.getClass().getDeclaredField("mEdgeSize");
            edgeSizeField.setAccessible(true);
            int edgeSize = edgeSizeField.getInt(leftDragger);
            DisplayMetrics dm = new DisplayMetrics();
            activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
            edgeSizeField.setInt(leftDragger, Math.max(edgeSize, (int) (dm.widthPixels * displayWidthPercentage)));
        } catch (Exception e) {
        }
    }
    /***
     * 方法一对集合进行深拷贝 注意需要对泛型类进行序列化(实现Serializable)
     *
     * @param srcList
     * @param 
     * @return
     */
    public static  ArrayList depCopy(ArrayList srcList) {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(srcList);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream inStream = new ObjectInputStream(byteIn);
            ArrayList destList = (ArrayList) inStream.readObject();
            return destList;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 方法一对集合进行深拷贝 注意需要对泛型类进行序列化(实现Serializable)
     *
     * @param srcList
     * @param 
     * @return
     */
    public static  List depCopy(List srcList) {
        ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
        try {
            ObjectOutputStream out = new ObjectOutputStream(byteOut);
            out.writeObject(srcList);

            ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
            ObjectInputStream inStream = new ObjectInputStream(byteIn);
            List destList = (List) inStream.readObject();
            return destList;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 隐藏软键盘(有输入框)
     * @param context
     * @param mEditText
     */
    public static void hideSoftKeyboard(@NonNull Context context, @NonNull EditText mEditText)
    {
        InputMethodManager inputmanger = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        inputmanger.hideSoftInputFromWindow(mEditText.getWindowToken(), 0);
    }
    /**
     * 去掉文字加粗
     * @param textView
     */
    public static void setTextUnBold(TextView textView){
        TextPaint tp = textView.getPaint();
        tp.setFakeBoldText(false);
    }
    /**
     * 文字加粗
     * @param textView
     */
    public static void setTextBold(TextView textView){
        if(textView!=null){
            TextPaint tp = textView.getPaint();
            tp.setFakeBoldText(true);
        }
    }
    //获取屏幕的高度
    public static int getScreenHeight(Context context) {
//        DisplayMetrics dm = new DisplayMetrics();
//
//        // 测试设备 1440*2960 --- SDK VERSION 24 --- 包含虚拟功能键
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
//            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getRealMetrics(dm); // 包含虚拟功能键高度 dm.heightPixels = 2960
//        } else {
//            ((WindowManager) context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm); // 不包含虚拟功能键高度 dm.heightPixels = 2768
//        }
//
//        int WIDTH = Math.min(dm.widthPixels, dm.heightPixels);
//        int HEIGHT = Math.max(dm.widthPixels, dm.heightPixels);
//        return HEIGHT;

        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        int height = wm.getDefaultDisplay().getHeight();
        return height;

    }
    public static void  setLayoutSlideHeight(Context context,WindowManager.LayoutParams lp, boolean monitor_flag_hide, int select_layout_heigh,  int sentiFilterHeight,int verticalSlideOffset){
        Logger.debug("LayoutHeight","ScreenHeight="+getScreenHeight(context)+"|select_layout_heigh="+CommonManager.px2dp(select_layout_heigh)+"|sentiFilterHeight="+CommonManager.px2dp(sentiFilterHeight));
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                lp.height = getScreenHeight(context)  - (sentiFilterHeight-verticalSlideOffset)+StatusBarCompat.getStatusBarHeight(context);
            }else {
                lp.height = getScreenHeight(context) - (sentiFilterHeight-verticalSlideOffset);
            }
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                lp.height = getScreenHeight(context) - (sentiFilterHeight-verticalSlideOffset);
            }else{
                lp.height = getScreenHeight(context) - CommonManager.getStatusBarHeight() - sentiFilterHeight;
            }
        }
    }
    public static void  setLayoutHeight(Context context,WindowManager.LayoutParams lp, boolean monitor_flag_hide, int select_layout_heigh,  int sentiFilterHeight){
        if(monitor_flag_hide){
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                    lp.height = getScreenHeight(context) -select_layout_heigh+StatusBarCompat.getStatusBarHeight(context);
                }else {
                    lp.height = getScreenHeight(context) -select_layout_heigh;
                }
            }else{
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                    lp.height = getScreenHeight(context) -select_layout_heigh;
                }else{
                    lp.height = getScreenHeight(context) - CommonManager.getStatusBarHeight()-select_layout_heigh;
                }
            }
        }else{
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q){
                    lp.height = getScreenHeight(context) - sentiFilterHeight;
                }else{
                    lp.height = getScreenHeight(context) - sentiFilterHeight-StatusBarCompat.getStatusBarHeight(context);
                }
            }else {
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
                    lp.height = getScreenHeight(context)  - sentiFilterHeight-StatusBarCompat.getStatusBarHeight(context);
                }else{
                    lp.height = getScreenHeight(context) - CommonManager.getStatusBarHeight() - sentiFilterHeight;
                }
            }
        }
    }
    public  static void initRecyclerView(Context context, RecyclerView recyclerView, CommonAdapter adapter,boolean lineFlag){
        if(recyclerView!=null && adapter!=null){
            recyclerView.setAdapter(adapter);
            recyclerView.setLayoutManager(new LinearLayoutManager(context));
            if(lineFlag){
                recyclerView.addItemDecoration(new RecyclerItemDecoration(context));
            }
        }
    }
    public static void initRecyclerGridView(Context context, RecyclerView recyclerView, CommonAdapter adapter,int spanCount,float spacing){
        recyclerView.setLayoutManager(new GridLayoutManager(context,spanCount){
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        });
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, CommonManager.dp2px(spacing), false));
        recyclerView.setFocusable(false);
        recyclerView.setAdapter(adapter);
    }
    public static void initRecyclerGridView(Context context, RecyclerView recyclerView, CommonAdapter adapter,int spanCount,float spacing,boolean scrollFlag){
        recyclerView.setLayoutManager(new GridLayoutManager(context,spanCount){
            @Override
            public boolean canScrollVertically() {
                return scrollFlag;
            }
        });
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(spanCount, CommonManager.dp2px(spacing), false));
        recyclerView.setFocusable(false);
        recyclerView.setAdapter(adapter);
    }
    public static void setDefHeadIcon(Context context, ImageView imageView, String originType, String author_url){
        int defaultRid=R.drawable.icon_def_head;
        if(originType!=null){
            switch (originType){
                case "wb" :
                    defaultRid=R.drawable.icon_default_wb;
                    break;
                case "lt" :
                    defaultRid=R.drawable.icon_default_lt;
                    break;
                case "bk" :
                    defaultRid=R.drawable.icon_default_bk;
                    break;
                case "baokan" :
                    defaultRid=R.drawable.icon_default_baokan;
                    break;
                case "app" :
                    defaultRid=R.drawable.icon_default_app;
                    break;
                case "sp" :
                    defaultRid=R.drawable.icon_default_sp;
                    break;
                case "wx" :
                    defaultRid=R.drawable.icon_default_wx;
                    break;
                case "zw" :
                    defaultRid=R.drawable.icon_default_zw;
                    break;
                case "xw" :
                    defaultRid=R.drawable.icon_default_xw;
                    break;
                case "wz" :
                    defaultRid=R.drawable.icon_default_wz;
                    break;
                case "jw" :
                    defaultRid=R.drawable.icon_default_jw;
                    break;
            }
        }
        if(!isEmpty(author_url)){
            GlideUtils.LoadCircleHomeDefImage(context,author_url,imageView,R.color.color_e2e2e2,defaultRid);
        }else{
            imageView.setImageResource(defaultRid);
        }
    }
    public static SentiNewCondition setFullTextSentiCondition(SentiCondition sentiCondition) {
        SentiNewCondition searchSetCondition = new SentiNewCondition();
        if(sentiCondition!=null) {
            if(sentiCondition.getInformationContentType()!=null){
                searchSetCondition.setInformationContentType(sentiCondition.getInformationContentType());
            }
            if(YqtApplication.getInstance.isNewType()){
                if (sentiCondition.getOriginTypeFirstList() != null) {
                    searchSetCondition.setOriginTypeFirstList(sentiCondition.getOriginTypeFirstList());
                }
                if (sentiCondition.getOriginTypeSecondList() != null) {
                    searchSetCondition.setOriginTypeSecondList(sentiCondition.getOriginTypeSecondList());
                }
                if (sentiCondition.getOriginTypeThirdList() != null) {
                    searchSetCondition.setOriginTypeThirdList(sentiCondition.getOriginTypeThirdList());
                }
            }

            if (!TextUtils.isEmpty(sentiCondition.getKeyword())) {
                searchSetCondition.setSearchKeyword(sentiCondition.getKeyword());
            }
            if (sentiCondition.getSearchType() != null) {
                searchSetCondition.setSearchType(sentiCondition.getSearchType());
            }
            if (!TextUtils.isEmpty(sentiCondition.getSearchSecondKeyword())) {
                searchSetCondition.setSearchSecondKeyword(sentiCondition.getSearchSecondKeyword());
            }
            if (!TextUtils.isEmpty(sentiCondition.getInvolveWay())) {
                searchSetCondition.setInvolveWay(CommonManager.toInt(sentiCondition.getInvolveWay()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getKeywordId())) {
                searchSetCondition.setKeywordId(CommonManager.toInt(sentiCondition.getKeywordId()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getOrder())) {
                searchSetCondition.setOrder(CommonManager.toInt(sentiCondition.getOrder()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getSort())) {
                searchSetCondition.setSort(CommonManager.toInt(sentiCondition.getSort()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getTimeDomain())) {
                searchSetCondition.setTimeDomain(CommonManager.toInt(sentiCondition.getTimeDomain()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getStartTime())) {
                searchSetCondition.setStartTime(sentiCondition.getStartTime());
            }
            if (!TextUtils.isEmpty(sentiCondition.getEndTime())) {
                searchSetCondition.setEndTime(sentiCondition.getEndTime());
            }
            if (!TextUtils.isEmpty(sentiCondition.getAttribute())) {
                searchSetCondition.setOptions(CommonManager.toInt(sentiCondition.getAttribute()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getOrigin())) {
                searchSetCondition.setOrigins(sentiCondition.getOrigin());
            }
            if (!TextUtils.isEmpty(sentiCondition.getNewlstSelect())) {
                searchSetCondition.setPresentResult(CommonManager.toInt(sentiCondition.getNewlstSelect()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getAccurateSwitch())) {
                searchSetCondition.setAccurateSwitch(CommonManager.toInt(sentiCondition.getAccurateSwitch()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getComblineflg())) {
                searchSetCondition.setComblineflg(CommonManager.toInt(sentiCondition.getComblineflg()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getWebSiteId())) {
                searchSetCondition.setWebSiteId(CommonManager.toInt(sentiCondition.getWebSiteId()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getIsRoot())) {
                searchSetCondition.setSearchRootWb(CommonManager.toInt(sentiCondition.getIsRoot()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getBloggerAuth())) {
                searchSetCondition.setBloggerAuth(CommonManager.toInt(sentiCondition.getBloggerAuth()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getFansLevelStart())) {
                searchSetCondition.setFansLevelStart(CommonManager.toInt(sentiCondition.getFansLevelStart()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getFansLevelEnd())) {
                searchSetCondition.setFansLevelEnd(CommonManager.toInt(sentiCondition.getFansLevelEnd()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getMatchingMode())) {
                searchSetCondition.setMatchType(CommonManager.toInt(sentiCondition.getMatchingMode()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getKeywordProvince())) {
                searchSetCondition.setKeywordProvince(sentiCondition.getKeywordProvince());
            }
            if (!TextUtils.isEmpty(sentiCondition.getTitleHs())) {
                searchSetCondition.setTitleHs(sentiCondition.getTitleHs());
            }
            if (!TextUtils.isEmpty(sentiCondition.getWeiboType())) {
                searchSetCondition.setWeiboType(CommonManager.toInt(sentiCondition.getWeiboType()));
            }
            if (!TextUtils.isEmpty(sentiCondition.getBloggerAuthenticationStatusMultiple())) {
                searchSetCondition.setBloggerAuthenticationStatusMultiple(sentiCondition.getBloggerAuthenticationStatusMultiple());
            }
            if (!TextUtils.isEmpty(sentiCondition.getWeiboTypeMultiple())) {
                searchSetCondition.setWeiboTypeMultiple(sentiCondition.getWeiboTypeMultiple());
            }
            if (!TextUtils.isEmpty(sentiCondition.getSearchRootWbMultiple())) {
                searchSetCondition.setSearchRootWbMultiple(sentiCondition.getSearchRootWbMultiple());
            }
            if (!TextUtils.isEmpty(sentiCondition.getSensitiveWordsFrom())) {
                searchSetCondition.setUserOptions(CommonManager.toInt(sentiCondition.getSensitiveWordsFrom()));
            }
        }
        return searchSetCondition;
    }
    public static SentiNewCondition setSentiNewCondition(SentiCondition sentiCondition) {
        SentiNewCondition searchSetCondition = new SentiNewCondition();
        if(sentiCondition!=null){
            if(sentiCondition.getInformationContentType()!=null){
                searchSetCondition.setInformationContentType(sentiCondition.getInformationContentType());
            }
            if(YqtApplication.getInstance.isNewType()){
                if(sentiCondition.getOriginTypeFirstList()!=null){
                    searchSetCondition.setOriginTypeFirstList(sentiCondition.getOriginTypeFirstList());
                }
                if(sentiCondition.getOriginTypeSecondList()!=null){
                    searchSetCondition.setOriginTypeSecondList(sentiCondition.getOriginTypeSecondList());
                }
                if(sentiCondition.getOriginTypeThirdList()!=null){
                    searchSetCondition.setOriginTypeThirdList(sentiCondition.getOriginTypeThirdList());
                }
            }

            if(sentiCondition.getSearchType()!=null){
                searchSetCondition.setSearchType(sentiCondition.getSearchType());
            }
            if(!TextUtils.isEmpty(sentiCondition.getSearchSecondKeyword())){
                searchSetCondition.setSearchSecondKeyword(sentiCondition.getSearchSecondKeyword());
            }
            if(sentiCondition.getDataView()!=null){
                searchSetCondition.setDataView(sentiCondition.getDataView());
            }
            if(!TextUtils.isEmpty(sentiCondition.getInvolveWay())){
                searchSetCondition.setInvolveWay(CommonManager.toInt(sentiCondition.getInvolveWay()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getKeywordId())){
                searchSetCondition.setKeywordId(CommonManager.toInt(sentiCondition.getKeywordId()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getOrder())){
                searchSetCondition.setOrder(CommonManager.toInt(sentiCondition.getOrder()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getSort())){
                searchSetCondition.setSort(CommonManager.toInt(sentiCondition.getSort()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getTimeDomain())){
                searchSetCondition.setTimeDomain(CommonManager.toInt(sentiCondition.getTimeDomain()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getStartTime())){
                searchSetCondition.setStartTime(sentiCondition.getStartTime());
            }
            if(!TextUtils.isEmpty(sentiCondition.getEndTime())){
                searchSetCondition.setEndTime(sentiCondition.getEndTime());
            }
            if(!TextUtils.isEmpty(sentiCondition.getAttribute())){
                searchSetCondition.setOptions(CommonManager.toInt(sentiCondition.getAttribute()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getOrigin())){
                searchSetCondition.setOrigins(sentiCondition.getOrigin());
            }
            if(!TextUtils.isEmpty(sentiCondition.getNewlstSelect())){
                searchSetCondition.setPresentResult(CommonManager.toInt(sentiCondition.getNewlstSelect()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getAccurateSwitch())){
                searchSetCondition.setAccurateSwitch(CommonManager.toInt(sentiCondition.getAccurateSwitch()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getComblineflg())){
                searchSetCondition.setComblineflg(CommonManager.toInt(sentiCondition.getComblineflg()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getWebSiteId())){
                searchSetCondition.setWebSiteId(CommonManager.toInt(sentiCondition.getWebSiteId()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getIsRoot())){
                searchSetCondition.setSearchRootWb(CommonManager.toInt(sentiCondition.getIsRoot()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getBloggerAuth())){
                searchSetCondition.setBloggerAuth(CommonManager.toInt(sentiCondition.getBloggerAuth()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getFansLevelStart())){
                searchSetCondition.setFansLevelStart(CommonManager.toInt(sentiCondition.getFansLevelStart()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getFansLevelEnd())){
                searchSetCondition.setFansLevelEnd(CommonManager.toInt(sentiCondition.getFansLevelEnd()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getMatchingMode())){
                searchSetCondition.setMatchType(CommonManager.toInt(sentiCondition.getMatchingMode()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getKeywordProvince())){
                searchSetCondition.setKeywordProvince(sentiCondition.getKeywordProvince());
            }
            if(!TextUtils.isEmpty(sentiCondition.getTitleHs())){
                searchSetCondition.setTitleHs(sentiCondition.getTitleHs());
            }
            if(!TextUtils.isEmpty(sentiCondition.getWeiboType())){
                searchSetCondition.setWeiboType(CommonManager.toInt(sentiCondition.getWeiboType()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getBloggerAuthenticationStatusMultiple())){
                searchSetCondition.setBloggerAuthenticationStatusMultiple(sentiCondition.getBloggerAuthenticationStatusMultiple());
            }
            if(!TextUtils.isEmpty(sentiCondition.getWeiboTypeMultiple())){
                searchSetCondition.setWeiboTypeMultiple(sentiCondition.getWeiboTypeMultiple());
            }
            if(!TextUtils.isEmpty(sentiCondition.getSearchRootWbMultiple())){
                searchSetCondition.setSearchRootWbMultiple(sentiCondition.getSearchRootWbMultiple());
            }
            if(!TextUtils.isEmpty(sentiCondition.getSensitiveWordsFrom())){
                searchSetCondition.setUserOptions(CommonManager.toInt(sentiCondition.getSensitiveWordsFrom()));
            }
            if(!TextUtils.isEmpty(sentiCondition.getPostStatus())){
                searchSetCondition.setBlogPostsStatus(CommonManager.toInt(sentiCondition.getPostStatus()));
            }
        }
        return searchSetCondition;
    }
    public static SentiCondition setSentiCondition(SentiCondition sentiCondition , UserSearchSet userSearchSet){
        if (userSearchSet != null && sentiCondition != null) {
            if(userSearchSet.getInformationContentType()!=null){
                sentiCondition.setInformationContentType(userSearchSet.getInformationContentType());
            }
            if(YqtApplication.getInstance.isNewType()){
                if(!TextUtils.isEmpty(userSearchSet.getOriginTypeFirst())){
                    String [] arrFirst=userSearchSet.getOriginTypeFirst().split(",");
                    List list = Arrays.asList(arrFirst);
                    sentiCondition.setOriginTypeFirstList(new ArrayList<>(list));
                }
                if(!TextUtils.isEmpty(userSearchSet.getOriginTypeSecond())){
                    String [] arrSecond=userSearchSet.getOriginTypeSecond().split(",");
                    List list = Arrays.asList(arrSecond);
                    sentiCondition.setOriginTypeSecondList(new ArrayList<>(list));
                }
                if(!TextUtils.isEmpty(userSearchSet.getOriginTypeThird())){
                    String [] arr=userSearchSet.getOriginTypeThird().split(",");
                    List list = Arrays.asList(arr);
                    sentiCondition.setOriginTypeThirdList(new ArrayList<>(list));
                }
            }

            if(userSearchSet.getMatchingMode()==0){
                sentiCondition.setMatchingMode("3");
            }else{
                sentiCondition.setMatchingMode(String.valueOf(userSearchSet.getMatchingMode()));
            }
            if(userSearchSet.getDataView()!=null){
                sentiCondition.setDataView(userSearchSet.getDataView());
            }
            if (CommonManager.isNotEmpty(userSearchSet.getTimeDomain())) {
                sentiCondition.setTimeDomain(userSearchSet.getTimeDomain());
            }
            if (CommonManager.isNotEmpty(userSearchSet.getSourceWebType())) {
                sentiCondition.setOrigin(userSearchSet.getSourceWebType());
            }
            if (userSearchSet.getOrder()!=null) {
                sentiCondition.setOrder(String.valueOf(userSearchSet.getOrder()));
            }
            if (userSearchSet.getSort()!=null) {
                sentiCondition.setSort(String.valueOf(userSearchSet.getSort()));
            }
            if (CommonManager.isNotEmpty(userSearchSet.getAttribute())) {
                sentiCondition.setAttribute(userSearchSet.getAttribute());
            }
            if (CommonManager.isNotEmpty(userSearchSet.getNewlstSelect())) {
                if(UserManager.getUserBean().getWiseChoiceSwitch()!=null && UserManager.getUserBean().getWiseChoiceSwitch()==1){//智选
                    sentiCondition.setNewlstSelect(Utils.checkEmpty(userSearchSet.getNewlstSelect()));
                }else{
                    if(!TextUtils.isEmpty(userSearchSet.getNewlstSelect()) && userSearchSet.getNewlstSelect().equals("5")){
                        sentiCondition.setNewlstSelect("1");
                    }else{
                        sentiCondition.setNewlstSelect(Utils.checkEmpty(userSearchSet.getNewlstSelect()));
                    }
                }
            }
            if (userSearchSet.getAccurateSwitch()!=null) {
                sentiCondition.setAccurateSwitch(String.valueOf(userSearchSet.getAccurateSwitch()));
            }
            if (userSearchSet.getComblineflg()!=null) {
                sentiCondition.setComblineflg(String.valueOf(userSearchSet.getComblineflg()));
            }
            if (userSearchSet.getFilterWebsiteType()!=null) {
                sentiCondition.setWebSiteId(String.valueOf(userSearchSet.getFilterWebsiteType()));
            }
            if (userSearchSet.getIsRoot()!=null) {
                sentiCondition.setIsRoot(String.valueOf(userSearchSet.getIsRoot()));
            }
            if (userSearchSet.getBloggerAuth()!=null) {
                sentiCondition.setBloggerAuth(String.valueOf(userSearchSet.getBloggerAuth()));
            }
            if (userSearchSet.getFollowersCountFrom()!=null) {
                sentiCondition.setFansLevelStart(String.valueOf(userSearchSet.getFollowersCountFrom()));
            }
            if (userSearchSet.getFollowersCountTo()!=null) {
                sentiCondition.setFansLevelEnd(String.valueOf(userSearchSet.getFollowersCountTo()));
            }
            if (userSearchSet.getSensitiveWordsFrom()!=null) {
                sentiCondition.setSensitiveWordsFrom(String.valueOf(userSearchSet.getSensitiveWordsFrom()));
            }
            if (userSearchSet.getInvolveWay()!=null) {
                sentiCondition.setInvolveWay(String.valueOf(userSearchSet.getInvolveWay()));
            }
            if (CommonManager.isNotEmpty(userSearchSet.getKeywordProvince())) {
                sentiCondition.setKeywordProvince(userSearchSet.getKeywordProvince());
            }
            if (userSearchSet.getWeiboType()!=null) {
                sentiCondition.setWeiboType(String.valueOf(userSearchSet.getWeiboType()));
            }
            if (CommonManager.isNotEmpty(userSearchSet.getBloggerAuthenticationStatusMultiple()))
                sentiCondition.setBloggerAuthenticationStatusMultiple(userSearchSet.getBloggerAuthenticationStatusMultiple());
            if (CommonManager.isNotEmpty(userSearchSet.getWeiboTypeMultiple()))
                sentiCondition.setWeiboTypeMultiple(userSearchSet.getWeiboTypeMultiple());
            if (CommonManager.isNotEmpty(userSearchSet.getSearchRootMultiple()))
                sentiCondition.setSearchRootWbMultiple(userSearchSet.getSearchRootMultiple());
        }
        return sentiCondition;
    }
//    public static  String objectToJsonStr(T obj) throws Exception {
//        if (null == obj)
//            return new JSONObject().toString();
//        StringWriter str = new StringWriter();
//        ObjectMapper mapper = new ObjectMapper();
//        mapper.writeValue(str, obj);
//        return str.toString();
//    }
    /**
     * 将java对象转换成json字符串
     *
     * @param bean
     * @return
     */

    public static String beanToJson(Object bean) {
        if(bean!=null){
            Gson gson = new Gson();
            String jsonStr = gson.toJson(bean);
            System.out.println(jsonStr);
            return jsonStr;
        }else{
          return "";
        }
    }
    public static  List jsonToBean(String res){
        //json转换为list
        Gson gson = new Gson();
        return gson.fromJson(res, new TypeToken>(){}.getType());
    }

    /**
     * public static  T notNull(final T argument, final String name) {
     *         if (argument == null) {
     *             throw new IllegalArgumentException(name + " may not be null");
     *         }
     *         return argument;
     *     }
     * @param context
     * @param textView
     */
    public static void setBackTextView(Context context,TextView textView) {
        Utils.setTypefaceTwo(context,textView,"\ue677",R.color.color_333333,25);
    }

    public int spToPixels(Context context,final float sp) {
        return (int) Math.ceil(TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics()));
    }
    /**
     * 使用Matrix将Bitmap压缩到指定大小
     * @param bitmap
     * @param w
     * @param h
     * @return
     */
    public static Bitmap resizeBitmap(Bitmap bitmap, int w, int h)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();

        float scaleWidth = ((float) w) / width;
        float scaleHeight = ((float) h) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);

        return Bitmap.createBitmap(bitmap, 0, 0, width,
                height, matrix, true);
    }
    public static View getLayoutView(android.content.Context context, int rLayout){
        return LayoutInflater.from(context).inflate(rLayout, null);
    }
    private void test(){
        List comKeywordList=new ArrayList<>();
        for(ComKeyword comKeyword : comKeywordList){
            if(comKeyword.getCompanyName().equals("全部")){
                comKeywordList.remove(comKeyword);
            }
        }
    }
    public static void setTypeface(Context context, TextView textView, String code,Integer textColor){
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/iconfont_all.ttf");
        textView.setTypeface(typeface);
        //"\ue70a"
        if(textColor!=null){
            textView.setTextColor(context.getResources().getColor(textColor));
        }
        textView.setText(code);
    }
    public static void setTypefaceTwo(Context context, TextView textView, String code,Integer textColor,float textSize){
        Typeface typeface = Typeface.createFromAsset(context.getAssets(), "font/iconfont_all.ttf");
        if(textView!=null){
            textView.setTypeface(typeface);
            textView.setTextSize(textSize);
            //"\ue70a"
            if(textColor!=null){
                textView.setTextColor(context.getResources().getColor(textColor));
            }
            textView.setText(code);
        }
    }
    public static boolean isVIVO() {
        String manufacturer = Build.MANUFACTURER;
        if ("vivo".equalsIgnoreCase(manufacturer)) {
            return true;
        }
        return false;
    }
    public static boolean isMeiZu() {
        return Build.MANUFACTURER.equalsIgnoreCase("Meizu");
    }
    public static boolean isXiaomi() {
        return Build.MANUFACTURER.equalsIgnoreCase("Xiaomi");
    }
    public static boolean isHuawei() {
        return Build.MANUFACTURER.equalsIgnoreCase("huawei");
    }
    public static boolean isOppo() {
        return Build.MANUFACTURER.equalsIgnoreCase("OPPO");
    }
    public static void setTextViewDrawableRight(Context context, TextView textView,int res){
        Drawable drawable = context.getResources().getDrawable(res);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        textView.setCompoundDrawables(null,null,drawable,null);
    }
    public static int getStateBar(Context context){
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
    public static int getStatusBarHeight(Activity activity) {
        Rect frame = new Rect();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
            activity.getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
        }
        int statusBarHeight = frame.top;
        return statusBarHeight;
    }
//    static Handler handler=new Handler(){
//        @Override
//        public void handleMessage(Message msg) {
//            if (msg.what == 1123) { // 使用1123仅仅是因为在11月23号写的
//                Bitmap bitmap = (Bitmap)msg.obj;
//                BitmapDrawable drawable = new BitmapDrawable(null, bitmap);
//                drawable.addLevel(1, 1, drawable);
//                drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
//                drawable.setLevel(1);
//
//                CharSequence charSequence = tvDemo.getText();
//                tvDemo.setText(charSequence);
//                tvDemo.invalidate();
//            }
//        }
//    };
    public static class URLDrawable extends BitmapDrawable {
        public Bitmap bitmap;

        @Override
        public void draw(Canvas canvas) {
            super.draw(canvas);
            if (bitmap != null) {
                canvas.drawBitmap(bitmap, 0, 0, getPaint());
            }
        }
    }
    public static void setLoadHtmlNoImage(Context context,TextView view,String srcString){
//        view.setText(Html.fromHtml(srcString, new MyImageGetter(context, view), null));
        Spanned spanned = Html.fromHtml(srcString,null,null);
        view.setText(spanned);
    }
    public static void setOnlyLoadHtml(Context context,TextView view,String srcString){
        if(!TextUtils.isEmpty(srcString) && view!=null){
            Spanned spanned = Html.fromHtml(srcString,new MyImageGetter(context, view),null);
            view.setText(spanned);
        }else{
            if(view!=null){
                view.setText("");
            }
        }
    }
    public static void setHtmlNeutralSrc(Context context,TextView view,String srcString){
        if(!TextUtils.isEmpty(srcString) && view!=null){
            String sText1 = "";
//        view.setText(Html.fromHtml(srcString, new MyImageGetter(context, view), null));
            Spanned spanned = Html.fromHtml(sText1+" "+srcString,new MyImageGetter(context, view),null);
            if (spanned instanceof SpannableStringBuilder) {
                ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class);
                if(imageSpans!=null && imageSpans.length>0){
                    for(int i=0;i";
            if(customFlag1!=null && customFlag1==2){
                sText1 = "";
            }else if(customFlag1!=null && customFlag1==5){
                sText1 = "";
            }else{
                sText1="";
            }
            sText1+="  ";
//        view.setText(Html.fromHtml(srcString, new MyImageGetter(context, view), null));
            Spanned spanned = Html.fromHtml(sText1+" "+srcString,new MyImageGetter(context, view),null);
            if (spanned instanceof SpannableStringBuilder) {
                ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class);
                if(imageSpans!=null && imageSpans.length>0){
                    for(int i=0;i";
            Spanned spanned = Html.fromHtml(sText1+" "+srcString,new MyImageGetter(context, view),null);
            if (spanned instanceof SpannableStringBuilder) {
                ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class);
                if(imageSpans!=null && imageSpans.length>0){
                    for(int i=0;i";
            Spanned spanned = Html.fromHtml(sText1+" "+srcString,new MyImageGetter(context, view),null);
            if (spanned instanceof SpannableStringBuilder) {
                ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class);
                if(imageSpans!=null && imageSpans.length>0){
                    for(int i=0;i";
//        final Html.ImageGetter imageGetter = new Html.ImageGetter() {
//            URLDrawable urlDrawable = new URLDrawable();
//            public Drawable getDrawable(String source) {
//                Drawable drawable=null;
//                if(source.startsWith("http://") || source.startsWith("https://")){
                    Glide.with(context).load(source).asBitmap().fitCenter().into(new SimpleTarget() {
                        @Override
                        public void onResourceReady(Bitmap resource, GlideAnimation glideAnimation) {
                            urlDrawable.bitmap = resource;
//                            Logger.getLogger().d("加载的图片,Width:" + resource.getWidth() + ",Height:" + resource.getHeight());
                            urlDrawable.setBounds(0, 0, resource.getWidth(), resource.getHeight());
                            view.invalidate();
                            view.setText(view.getText());//不加这句显示不出来图片,原因不详
                        }
                    });
//
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
//                            drawable.addLevel(0, 0, getResources().getDrawable(R.mipmap.ic_launcher));
                            drawable.setBounds(0, 0, 200, 200);

                            Bitmap bitmap;
                            try {
                                bitmap = BitmapFactory.decodeStream(new URL(source).openStream());
                                Message msg = handler.obtainMessage();
                                msg.what = 1123;
                                msg.obj = bitmap;
                                handler.sendMessage(msg);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
//                }else{
//                    int rId=Integer.parseInt(source);
//                    drawable=context.getResources().getDrawable(rId);
//                    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
//                    return drawable;
//                }
//                return drawable;
//            }
//        };
//        Spanned spanned = Html.fromHtml(sText1+" "+srcString,imageGetter,null);
//        if (spanned instanceof SpannableStringBuilder) {
//            ImageSpan[] imageSpans = spanned.getSpans(0, spanned.length(), ImageSpan.class);
//            for (ImageSpan imageSpan : imageSpans) {
//                int start = spanned.getSpanStart(imageSpan);
//                int end = spanned.getSpanEnd(imageSpan);
//                Drawable d = imageSpan.getDrawable();
                ImageSpan newImageSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
//                ImageSpan newImageSpan = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
//                ((SpannableStringBuilder) spanned).setSpan(newImageSpan, start, end, Spanned.SPAN_EXCLUSIVE_INCLUSIVE);
//                ((SpannableStringBuilder) spanned).removeSpan(imageSpan);
//            }
//        }
//        view.setText(spanned);
//
//    }

    private Drawable loadImageFromNetwork(String urladdr) {
        Drawable drawable = null;
        try{
            drawable = Drawable.createFromStream(new URL(urladdr).openStream(), "image.jpg");
        }catch(IOException e){

            Log.d("test",e.getMessage());

        }

        if(drawable == null){

            Log.d("test","null drawable");

        }else{

            Log.d("test","not null drawable");

        }

        return drawable;

    }

    public static void setTextPic(Context context,CharSequence text,TextView textView, int res){
//        SpannableString ss = new SpannableString("logo");
//        Drawable d = context.getResources().getDrawable(res);//得到drawable对象,即所要插入的图片
//        d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
//        ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);//用这个drawable对象代替字符串easy
//        //包括0但是不包括"easy".length()即:4。[0,4)。值得注意的是当我们复制这个图片的时候,实际是复制了"easy"这个字符串。
//        ss.setSpan(span, 0, "logo".length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
//        textView.setText("");
//        textView.append(ss);
//        textView.append(" "+text);
        textView.setText(text);
    }
    public static  void hiddenAnimation(View view){
        TranslateAnimation mHiddenAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF,
                0.0f, Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -0.0f);
        mHiddenAction.setDuration(500);
        view.startAnimation(mHiddenAction);
        view.setVisibility(View.GONE);
    }
    public static void showAnimation(View view){
        TranslateAnimation mShowAction = new TranslateAnimation(Animation.RELATIVE_TO_SELF, 0.0f,
                Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF,
                -0.0f, Animation.RELATIVE_TO_SELF, 0.0f);
        mShowAction.setDuration(500);
        view.startAnimation(mShowAction);
        view.setVisibility(View.VISIBLE);
    }
    /**
     * 解决Android studio log打印不全问题
     * @param tag
     * @param msg
     */
//    public static void i(String tag, String msg) {  //信息太长,分段打印
//        if(msg.length()>1000){
//            Log.i(tag, msg.substring(0, 1000));
//        }else{
//            Log.i(tag, msg);
//        }
//    }
    public static void i(String tag, String msg) {  //信息太长,分段打印
        //因为String的length是字符数量不是字节数量所以为了防止中文字符过多,
        //  把4*1024的MAX字节打印长度改为2001字符数
        int max_str_length = 2001 - tag.length();
        //大于4000时
        while (msg.length() > max_str_length) {
            Log.i(tag, msg.substring(0, max_str_length));
            msg = msg.substring(max_str_length);
        }
        //剩余部分
        Log.i(tag, msg);
    }
    public static AppVersionType getAppVersion(){
//        if(BuildConfig.LOG_DEBUG){
//            return YQT;
//        }else {
            switch (BuildConfig.appFlag){
                case Flag.cqyh :
                    return CQYH;
                case Flag.hnlt :
                    return HNLT;
                case Flag.mlqbt :
                    return MLQBT;
                case Flag.debug :
                case Flag.www :
                    return YQT;
                case Flag.yqgc :
                    return YQGC;
                case Flag.hbyq :
                    return HBYQ;
            }
//        }
        return null;
    }
}

你可能感兴趣的:(android,android,studio,java)