package com.tagmae.tsgame_erwang;

import com.tagmae.jsbridge.BridgeHandler;
import com.tagmae.jsbridge.BridgeWebView;
import com.tagmae.jsbridge.BridgeWebViewClient;
import com.tagmae.jsbridge.CallBackFunction;
import com.tagmae.jsbridge.DefaultHandler;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebViewExtension;
import com.tencent.smtt.export.external.interfaces.WebResourceError;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;


import com.jx.jyhd.R;
import com.jx.jyhd.simcpux.Constants;
import com.jx.jyhd.simcpux.MD5;
import com.jx.jyhd.simcpux.Util;
import com.jx.jyhd.simcpux.Wxistrue;
import com.jx.jyhd.simcpux.util.WeChatShareUtil;
import com.jx.jyhd.wxapi.WXEntryActivity;
import com.jx.jyhd.wxapi.WXPayEntryActivity;
import com.tsgame.tsgame_niuniu.Bean.Othervideoinfo;
import com.tsgame.tsgame_niuniu.Bean.videoinfobean;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Picture;
import android.graphics.PixelFormat;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.util.Xml;
import android.view.Display;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationClientOption.AMapLocationMode;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.LocationSource.OnLocationChangedListener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader.ImageContainer;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.ImageRequest;
import com.badoo.mobile.util.WeakHandler;
import com.ceshi.tsgame.shake.NeedForSound;
import com.ceshi.tsgame.shake.ShakeListener;
import com.ceshi.tsgame.shake.ShakeListener.OnShakeListenerCallBack;
import com.game.webgame.network.Volleyinterface;
import com.game.webgame.network.Volleyinterface1;
import com.game.webgame.network.register;
import com.game.webgame.network.volleymanager;
import com.game.webgame.view.SpUtil;
import com.game.webgame.view.dialogexit;
import com.game.webgame.view.dialogexit.onexitlistener;
import com.game.webgame.view.pmutil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nickming.view.AudioManager;
import com.nickming.view.AudioManager.AudioStageListener;
import com.nickming.view.DialogManager;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.util.Auth;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.bugly.crashreport.CrashReport.UserStrategy;
import com.tencent.bugly.crashreport.crash.h5.H5JavaScriptInterface;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXImageObject;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.smtt.export.external.interfaces.JsPromptResult;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.sdk.CacheManager;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm;
import com.tencent.smtt.sdk.WebView;

import com.tsgame.tsgame_niuniu.Bean.DragVideoinfoBean;
import com.tsgame.tsgame_niuniu.Bean.GamePayBean;
import com.tsgame.tsgame_niuniu.Bean.MaplocationInfo;
import com.tsgame.tsgame_niuniu.Bean.Wifinetworkbean;
import com.tsgame.tsgame_niuniu.Bean.phoneInfoBean;
import com.tsgame.tsgame_niuniu.Bean.savephotoURLBean;

import com.tsgame.tsgame_niuniu.Volley.IamgeCache.ImageCacheManager;
import com.tsgame.tsgame_niuniu.buglyutil.BuglyUtil;


import com.tsgame.tsgame_niuniu.receiver.ScreenListener;
import com.tsgame.tsgame_niuniu.simcpux.bean.sharetypeBean;
import com.tsgame.tsgame_niuniu.system.Myapplication;
import com.tsgame.tsgame_niuniu.system.WX_Myurl;
import com.tsgame.tsgame_niuniu.util.MediaFile;
import com.tsgame.tsgame_niuniu.util.Settingutil;
import com.tsgame.tsgame_niuniu.util.VibratorUtil;
import com.tsgame.tsgame_niuniu.util.apputil;
import com.tsgame.tsgame_niuniu.util.phoneutil;

import com.umeng.analytics.MobclickAgent;
import com.umeng.analytics.game.UMGameAgent;
import com.xys.libzxing.zxing.activity.CaptureActivity;
import com.yanzhenjie.nohttp.tools.NetUtil;

import com.yue.view.DragViewGroup;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
//import org.xianliao.im.sdk.api.ISGAPI;
//import org.xianliao.im.sdk.api.SGAPIFactory;
//import org.xianliao.im.sdk.constants.SGConstants;
//import org.xianliao.im.sdk.modelmsg.SGImageObject;
//import org.xianliao.im.sdk.modelmsg.SGLinkObject;
//import org.xianliao.im.sdk.modelmsg.SGMediaMessage;
//import org.xianliao.im.sdk.modelmsg.SendMessageToSG;
import org.xmlpull.v1.XmlPullParser;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.InvalidParameterException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//import cn.jpush.android.api.JPushInterface;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;
import io.agora.rtc.video.VideoCanvas;
import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

@SuppressLint({"NewApi", "HandlerLeak"})
public class webviewActivity extends AppCompatActivity implements
        OnClickListener, AudioStageListener, AMapLocationListener {
    BridgeWebView x5webview;
    private static final String mHomeUrl = "http://120.25.60.74:8001/index.html";
    private final String webviewurl = "file:///android_asset/niuniu/index1.html";
    private IWXAPI api;
    private IWXAPI msgApi;
    Dialog dialog;
    private boolean iscontinuouslocation = false;// 是否持续定位
    private UserStrategy strategy = null;

    private static final int THUMB_SIZE = 250;
    private static int service = 1;
    sharetypeBean bean;
    public static int aSd = 1;
    private DialogManager mDialogManager;
    private AudioManager mAudioManager;
    // 已经开始录音
    private static boolean isRecording = false;
    public boolean isForeground = true;// 是否在前台 true false
    private float mTime = 0;
    /**
     * 微信支付
     */
    PayReq req;
    private StringBuffer sb;
    Map<String, String> resultunifiedorder;

    static SharedPreferences Shared;
    private static String bitmappath;
    // ImageView image;
    private static final int STATE_NORMAL = 1;
    private static final int STATE_RECORDING = 2;
    private static final int STATE_WANT_TO_CANCEL = 3;
    Handler handler1 = new Handler();
    // Bitmap bitmap;
    static int x1; // 按下时的坐标
    static int y1;// 按下时的坐标
    private boolean mReady = false;
    private int mCurrentState = STATE_NORMAL;
    private boolean isautio = false;
    private UploadManager uploadManager;

    private String destFileDir = null;
    private String dirs = null;

    Bundle save;

    private SharedPreferences sp;

    File photofile1 = null;

    /**
     * 权限
     */
    public String[] carpermission = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.RECORD_AUDIO};
    String[] camerapermission1 = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    public String[] camerapermission = new String[]{Manifest.permission.CAMERA};

    private static final String PACKAGE_URL_SCHEME = "package:"; // 方案
    private boolean isDown = false;

    private boolean isStopPlay = false;// 是否停止了播放声音

    private boolean isPlayaudio = false;// 是否在播放

    // 准备三个常量
    private static final int MSG_AUDIO_PREPARED = 0X1110;
    private static final int MSG_VOICE_CHANGE = 0X111;
    private static final int MSG_DIALOG_DIMISS = 0X112;
    private static final int MSG_DIALOG_Audio_DIMISS = 0X113;
    // 升级

    // String m_newVerName; // 最新版的版本名 版本名
    String m_appNameStr = "tsgame_niuniu.apk"; // 下载到本地要给这个APP命的名字

    List<savephotoURLBean> testphoto;// 图片下载目录

    List<savephotoURLBean> testphoto1 = new ArrayList<savephotoURLBean>();// 图片下载目录

    private int photosize = 0;

    private Boolean getphotoistrue = true;

    BatteryReceiver batteryReceiver;
    WifiChangeBroadcastReceiver WifiChangeReceiver;
    MyNetReceiver myNetReceiver;

    ScreenListener screen;
    private int downloadnum = 0; // 下载失败次数

    private int downloadsum = 3; // 最多下载次数

    private OkHttpClient okclient = new OkHttpClient();

    List<String> photolist = new ArrayList<String>();

    Wifinetworkbean wifibean = new Wifinetworkbean();

    /**
     * 上次点击返回键的时间
     */
    private long lastBackPressed;
    /**
     * 上次点击返回键的时间
     */
    private static final int QUIT_INTERVAL = 1000;

    private static String uservoice = "";// 用户座位动画id

    // 初始化AMapLocationClientOption对象
    AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
    // 声明AMapLocationClient类对象
    public AMapLocationClient mLocationClient = null;

    OnLocationChangedListener mListener;
    /**
     * 权限
     */
    public String[] locationpermission = new String[]{
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE};

    WeakHandler mhandler = new WeakHandler(new Handler.Callback() {

        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_AUDIO_PREPARED:
                    // 显示应该是在audio end prepare之后回调

                    isRecording = true;

                    if (mDialogManager != null
                            && !webviewActivity.this.isFinishing()) {
                        try {
                            mDialogManager.showRecordingDialog();
                        } catch (Exception e) {
                            // TODO: handle exception
                        }

                    }

                    System.out.println("isRecording" + isRecording);
                    new Thread(mGetVoiceLevelRunnable).start();

                    // 需要开启一个线程来变换音量
                    break;
                case MSG_VOICE_CHANGE:
                    mDialogManager.updateVoiceLevel(mAudioManager.getVoiceLevel(7));

                    break;
                case MSG_DIALOG_DIMISS:

                    mDialogManager.dimissDialog();

                    break;
                case MSG_DIALOG_Audio_DIMISS:

                    if (isRecording) {
                        System.out.println("重新关闭");
                        mDialogManager.dimissDialog();
                        mAudioManager.cancel();
                        reset();

                    } else if (!isRecording && isautio) {
                        mhandler.sendEmptyMessageDelayed(MSG_DIALOG_Audio_DIMISS,
                                1000);// 持续1.3
                    }

                    break;

            }
            return false;
        }

    });

    @SuppressLint("HandlerLeak")
    Handler photohandler = new Handler() {
        public void handleMessage(Message msg) {

            int what = msg.what;

            if (what == 0) {
                Gson gson = new Gson();
                // for (int i = 0; i < testphoto1.size(); i++) {
                // savephotoURLBean bean = testphoto1.get(i);
                // }
                String json = gson.toJson(testphoto1);
//                String getphoto = "javascript:getphoto(" + "'" + json + "'"
//                        + ");";
//                webviewjh(getphoto);
                x5webview.callHandler("getphoto", json, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                    }
                });
                getphotoistrue = true;

            } else if (what == 1) {
                Bundle bundle = msg.getData();
                String photo = bundle.getString("photo");
                // savephoto(photo);
                if (getphotoistrue) {

                    savephoto(photo);
                } else {
                    Message msg1 = new Message();
                    msg1.what = 1;

                    Bundle bundel = new Bundle();
                    bundel.putString("photo", photo);

                    msg1.setData(bundel);
                    photohandler.sendMessageDelayed(msg1, 200);
                }

            }

        }
    };

    Handler playhandler = new Handler() {
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();
            String audiourl = bundle.getString("audiourl");
            String user = bundle.getString("user");
            if (!isPlayaudio) {
                isPlayaudio = true;
                play(audiourl, user);
            } else {
                Message msg1 = new Message();
                msg1.what = 1;
                Bundle bundel = new Bundle();
                bundel.putString("audiourl", audiourl);
                bundel.putString("user", user);
                msg1.setData(bundel);
                playhandler.sendMessageDelayed(msg1, 200);
            }
        }
    };

    Handler savehandler = new Handler() {
        public void handleMessage(Message msg) {

            if (Wxistrue.isshare) {
                Wxistrue.isshare = false;

                Bundle data = msg.getData();
                String bitpath = data.getString("bitpath");
                String type = data.getString("type");

                bean = new sharetypeBean();
                bean.setType(type);// 图片分享，分享到朋友圈
                bitmappath = bitpath;

                WXEntryActivity.setshareHandler(handler);

                if (type.equals("1")) {
                    try {
                        photosharefriend();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else if(type.equals("3")){
//                    if(!xlapi.isSGAppInstalled()){
//                        Toast.makeText(webviewActivity.this,"闲聊应用未安装，请先安装闲聊应用",Toast.LENGTH_SHORT).show();
//                        Wxistrue.isshare = true;
//                        Wxistrue.isphotoshare=true;
//                    }else{
//                        xlphotosharefriend();
//                    }
                }else{
                    try {
                        photosharefriends();

                    } catch (Exception e) {

                        Wxistrue.isshare = true;
                    }
                }
            }else{
                h5handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Wxistrue.isshare = true;
                    }
                },1000);
            }
        }
    };
    Handler payhandler = new Handler() {

        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    pay(1);
                    break;
                case 0:
                    pay(0);
                    break;
                default:
                    break;
            }
        }
    };

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @SuppressLint({"ShowToast"})
        @Override
        public void handleMessage(Message msg) {
            int success = msg.what;

            // Shared = SpUtil.getSharePerference(webviewActivity.this);

            if (success != 1) {

                Wxistrue.isshare = true;

                Wxistrue.isphotoshare = true;


                JSONObject json = new JSONObject();
                try {
                    json.put("success", success);

                    json.put("type", Wxistrue.sharetype);

                    System.out.println("---" + json.toString());
                    x5webview.callHandler("sharesuccess", json.toString(), new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {
                            //这里也是可以进行js回传的
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }


//                String sharesuccess = "javascript:sharesuccess(" + "'"
//                        + success + "'" + ",'" + Wxistrue.sharetype + "'"
//                        + ");";
//
////				 Toast.makeText(webviewActivity.this, "分享成功回调=="+Wxistrue.sharetype,
////				 1).show();
//
//                webviewjh(sharesuccess);
            }

            switch (msg.what) {
                case 1:

                    if (Shared == null) {
                        // Toast.makeText(webviewActivity.this, "Shared 为空",
                        // 1).show();
                    }

                    String openid = SpUtil.getStringSharedPerference(Shared,
                            "openid");
                    openid = openid.replaceAll("'", "");

                    String headimgurl = SpUtil.getStringSharedPerference(Shared,
                            "headimgurl");

                    headimgurl = headimgurl.replaceAll("'", "");

                    String nickname = SpUtil.getStringSharedPerference(Shared,
                            "nickname");
                    nickname = nickname.replaceAll("'", "");
                    String regEx = "[`~!@#$%^&*()+=|{}':;',//[//].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                    Pattern p = Pattern.compile(regEx);
                    Matcher m = p.matcher(nickname);
                    nickname = m.replaceAll("").trim();

                    String sex = SpUtil.getStringSharedPerference(Shared, "sex");
                    sex = sex.replaceAll("'", "");

                    String city = SpUtil.getStringSharedPerference(Shared, "city");
                    city = city.replaceAll("'", "");

                    String province = SpUtil.getStringSharedPerference(Shared,
                            "province");
                    province = province.replaceAll("'", "");

                    String unionid = SpUtil.getStringSharedPerference(Shared,
                            "unionid");
                    unionid = unionid.replaceAll("'", "");

                    Wxistrue.islogin = true;

                    // Toast.makeText(webviewActivity.this,
                    // "nickname"+nickname+"unionid="+unionid+"+headimgurl="+headimgurl+"openid="+openid+"sex="+sex+"city="+city+"province="+province,
                    // 1).show();

                    JSONObject json = new JSONObject();
                    try {
                        json.put("openid", openid);
                        json.put("headimgurl", headimgurl);
                        json.put("nickname", nickname);
                        json.put("sex", sex);
                        json.put("city", city);
                        json.put("province", province);
                        json.put("unionid", unionid);
                        System.out.println("---" + json.toString());
                        x5webview.callHandler("sharelogin", json.toString(), new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                //这里也是可以进行js回传的
                            }
                        });

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


//					String sharelogin = "javascript:sharelogin(" + "'" + openid
//							+ "'" + ",'" + headimgurl + "'" + ",'" + nickname + "'"
//							+ ",'" + sex + "'" + ",'" + city + "'" + ",'"
//							+ province + "'" + ",'" + unionid + "'" + ");";
//					System.out.println("sharelogin==" + sharelogin);

                    // commitLog.commitLog(webviewActivity.this, "android登陆"
                    // + sharelogin, sharelogin);

                    //	webviewjh(sharelogin);

                    CrashReport.setUserId(openid);
                    // setJPushAliasandTag();
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };

    Handler permissionHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (!hasPermission(camerapermission)) {

                        PermissionGen.needPermission(webviewActivity.this, 18,
                                camerapermission);
                    } else {

                        open();

                    }
                    break;
                case 2:

                    if (!hasPermission(camerapermission1)) {

                        PermissionGen.needPermission(webviewActivity.this, 22,
                                camerapermission1);
                    } else {

                        doTakePhoto();// 用户点击了从照相机获取

                    }

                    break;
                default:
                    break;
            }
        }

        ;
    };

    Handler paprehandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (!hasPermission(carpermission)) {

                        PermissionGen.needPermission(webviewActivity.this, 101,
                                carpermission);
                    } else {
                        try {
                            prepareAudio();
                        } catch (Exception e) {
                            // TODO: handle exception
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        ;

    };

    Handler shakehadler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case 1:
                    mShakeListener.start();
                    /**
                     * 摇一摇结束
                     */
                    // x5webview.loadUrl("javascript:shakeEnd();");
//                    String shakeEnd = "javascript:shakeEnd();";
//                    webviewjh(shakeEnd);
                    x5webview.callHandler("shakeEnd", "", new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });
                    break;

                default:
                    break;
            }
        }

        ;
    };
    // Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE
    String[] permissons = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
    private static WakeLock m_wklk;

    private Vibrator vibrator;
    public boolean isShake = false;
    private ShakeListener mShakeListener = null;
    boolean tai = true;

    private void preinitX5WebCore() {

        if (!QbSdk.isTbsCoreInited()) {
            // preinit只需要调用一次，如果已经完成了初始化，那么就直接构造view

            QbSdk.preInit(webviewActivity.this, null);// 设置X5初始化完成的回调接口

        }

    }

    @PermissionSuccess(requestCode = 22)
    public void succescamera() {
        doTakePhoto();
    }

    @PermissionFail(requestCode = 22)
    public void errorcamera() {

        List<String> nopermission = new ArrayList<String>();
        // String[] nopermission=null;
        for (int i = 0; i < camerapermission1.length; i++) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    camerapermission1[i])) {

                nopermission.add(camerapermission1[i]);
                System.out.println("拒绝");
            } else {
                // 勾选不再提示
                if (ContextCompat.checkSelfPermission(this,
                        camerapermission1[i]) == PackageManager.PERMISSION_DENIED) {
                    showMissingPermissionDialog();
                    break;
                }
            }
        }
        if (nopermission.size() > 0) {

            final String[] persions = new String[nopermission.size()];

            for (int i = 0; i < nopermission.size(); i++) {
                persions[i] = nopermission.get(i);
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("亲,当前应用缺少必要权限。不打开将无法使用");

            // 拒绝, 退出应用
            builder.setNegativeButton("退出",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();

                        }
                    });

            builder.setPositiveButton("打开",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            PermissionGen.needPermission(webviewActivity.this,
                                    22, persions);
                        }
                    });
            builder.show();
        }
    }

    /* 用来标识请求照相功能的activity */
    private static final int CAMERA_WITH_DATA = 3023;
    private String picName = "";// 用户拍照后保存的图片名称

    /* 拍照的照片存储位置 */
    private static File PHOTO_DIR = null;

    protected void doTakePhoto() {
        /**
         * 判断sd K 是否重载
         */
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {

            PHOTO_DIR = new File(Environment.getExternalStorageDirectory()
                    + "/TestPhotoPic");
        } else {
            PHOTO_DIR = new File(Environment.getDataDirectory()
                    + "/TestPhotoPic");
        }

        Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // 重新分解图片名称将-:的符号去掉
        picName = getPhotoFileName();
        picName = picName.replace("-", "");
        picName = picName.replace(":", "");
        File out = new File(PHOTO_DIR, picName);
        Uri uri = Uri.fromFile(out);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
        startActivityForResult(imageCaptureIntent, CAMERA_WITH_DATA);
    }

    /**
     * 用当前时间给取得的图片命名
     */
    @SuppressLint("SimpleDateFormat")
    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-ddHH:mm:ss");
        return dateFormat.format(date) + ".jpg";
    }

    static SoundPools SoundPool;

    @SuppressLint("InvalidWakeLockTag")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().setFormat(PixelFormat.TRANSLUCENT);

        /**
         * 方法一 保持屏幕唤醒
         */

        // getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
        // WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        hideNavigationBar();
        // 初始化分享面板
        SharePanelHelper.initSharePanel(this);
        setContentView(R.layout.x5webview);

        msgApi = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        strategy = new UserStrategy(getApplicationContext());
        strategy.setDeviceID("jxhd");
        strategy.setAppChannel("dhxj");  //设置渠道
        strategy.setAppVersion("3.4.4");      //App的版本
        strategy.setAppPackageName("com.jx.jyhd");  //App的包名
        strategy.setAppReportDelay(10000);

        x5webview = (BridgeWebView) findViewById(R.id.x5webview);
        findViewById(R.id.button2).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {
                Intent in = new Intent();

                in.putExtra("url", "http://debugx5.qq.com/ ");
                in.putExtra("title", "");
                in.putExtra("data", data);
                in.setClass(webviewActivity.this, openwebActivity1.class);
                // startActivity(in);
                startActivityForResult(in, 1001);


            }
        });

        SoundPool = new SoundPools();
        getclassname();

        findViewById(R.id.videotext).setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v) {

                Intent in = new Intent();

                in.putExtra("url", "http://debugx5.qq.com/ ");
                in.putExtra("title", "");
                in.putExtra("data", data);
                in.setClass(webviewActivity.this, openwebActivity1.class);
                // startActivity(in);
                startActivityForResult(in, 1001);
            }
        });

        Myapplication.getInstance().addActivity(webviewActivity.this);

        // getAllFilename("channel");

        okclient = new OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS).build();

        // final Button but = (Button) findViewById(R.id.qiantai);
        // but.setOnClickListener(new OnClickListener() {
        //
        // @Override
        // public void onClick(View v) {
        //
        // x5webview.loadUrl("javascript:dakashenyi();");
        //
        // }
        // });

        /*
         * *
         * 方法二
         */
        PowerManager pm = (PowerManager) getSystemService(POWER_SERVICE);
        // m_wklk = pm.newWakeLock
        // (PowerManager.ACQUIRE_CAUSES_WAKEUP |
        // PowerManager.SCREEN_DIM_WAKE_LOCK, "Tag");
        //

        m_wklk = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "cn");

        m_wklk.setReferenceCounted(false);

        m_wklk.acquire();// 设置保持唤醒

        start();
        // getWindow().setFormat(PixelFormat.TRANSLUCENT);
        save = savedInstanceState;
        initShake();
        initvideo();

        getAndroiodScreenProperty();//获取当前屏幕宽高含虚拟状态栏宽高

        if (!hasPermission(permissons)) {

            PermissionGen.needPermission(webviewActivity.this, 16, permissons);

        } else {

            initdate(save);
        }

        screen = new ScreenListener(this);
        screen.begin(new ScreenListener.ScreenStateListener() {

            @Override
            public void onUserPresent() {

                if (isForeground) {
                    service = 1;
                    // x5webview.loadUrl("javascript:appservice(" + "'" +
                    // service
                    // + "'" + ");");
                    if (isfinsh) {
//                        String appservice = "javascript:appservice(" + "'"
//                                + service + "'" + ");";
//                        webviewjh(appservice);
                        x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                //这里也是可以进行js回传的
                            }
                        });
                    }

                }
            }

            @Override
            public void onScreenOn() {
                if (isForeground) {
                    service = 1;
                    // x5webview.loadUrl("javascript:appservice(" + "'" +
                    // service
                    // + "'" + ");");
                    if (isfinsh) {
//                        String appservice = "javascript:appservice(" + "'"
//                                + service + "'" + ");";
//                        webviewjh(appservice);
                        x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                //这里也是可以进行js回传的
                            }
                        });
                    }

                }

                // Toast.makeText(webviewActivity.this, "开屏", 1).show();

            }

            @Override
            public void onScreenOff() {
                // Toast.makeText(webviewActivity.this, "锁屏", 1).show();
                service = 2;
                if (isfinsh) {
//                    String appservice = "javascript:appservice(" + "'"
//                            + service + "'" + ");";
//                    webviewjh(appservice);
                    x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {
                            //这里也是可以进行js回传的
                        }
                    });
                }

                // x5webview.loadUrl("javascript:appservice(" + "'" + service
                // + "'" + ");");
            }
        });

    }

    // 隐藏虚拟按键
    public void hideNavigationBar() {
        int uiFlags = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                | View.SYSTEM_UI_FLAG_FULLSCREEN; // hide status bar

        if (android.os.Build.VERSION.SDK_INT >= 19) {
            uiFlags |= 0x00001000;    //SYSTEM_UI_FLAG_IMMERSIVE_STICKY: hide navigation bars - compatibility: building API level is lower thatn 19, use magic number directly for higher API target level
        } else {
            uiFlags |= View.SYSTEM_UI_FLAG_LOW_PROFILE;
        }
        getWindow().getDecorView().setSystemUiVisibility(uiFlags);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideNavigationBar();
        }
    }

    private void getclassname() {
        ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTasks = manager.getRunningTasks(1);
        RunningTaskInfo cinfo = runningTasks.get(0);
        ComponentName component = cinfo.topActivity;
        System.out.println("current activity is " + component.getClassName());
        apputil.activityname = component.getClassName();

    }


    private void initShake() {
        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        NeedForSound.getInstance().addSound(this);
        mShakeListener = new ShakeListener(this);
        mShakeListener.setOnShakeListener(shakeListener);
        mShakeListener.stop();
    }

    OnShakeListenerCallBack shakeListener = new OnShakeListenerCallBack() {
        public void onShake() {
            // startShakeAnim(); // 开始 摇一摇手掌动画
            mShakeListener.stop();

            if (apputil.Voicetype == 1) {
                NeedForSound.getInstance().playStartSound();
            }

            // NeedForSound.getInstance().playEndSound();
            // 获取手机震动服务
            // if(apputil.shaketype==0){
            // vibrator.vibrate(new long[] { 100, 300, 100, 300 }, -1);
            // }

            shakehadler.sendEmptyMessageDelayed(1, 1000);

        }
    };

    private void inithandler() {

        OkHttpPhotoServer.setPhotoHandler(savehandler);

        // 注册广播接受者java代码
        IntentFilter intentFilter = new IntentFilter(
                Intent.ACTION_BATTERY_CHANGED);

        // 创建广播接受者对象
        batteryReceiver = new BatteryReceiver();
        // 注册receiver
        registerReceiver(batteryReceiver, intentFilter);

        /**
         * wifi 信号改变
         *
         */
        WifiChangeReceiver = new WifiChangeBroadcastReceiver();
        registerReceiver(WifiChangeReceiver, new IntentFilter(
                WifiManager.RSSI_CHANGED_ACTION));
        myNetReceiver = new MyNetReceiver();
        // 网络状态改变

        IntentFilter mFilter = new IntentFilter();
        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(myNetReceiver, mFilter);

    }

    protected void savephoto(String string) {

        try {

            getphotoistrue = false;

            testphoto1.clear();
            Gson gson = new Gson();
            Type type = new TypeToken<List<savephotoURLBean>>() {
            }.getType();

            System.out.println(string);

            testphoto = new ArrayList<savephotoURLBean>();

            testphoto = gson.fromJson(string, type);
            photosize = 0;

            System.out.println("-----" + string);

            if (testphoto.size() > 0) {
                for (int i = 0; i < testphoto.size(); i++) {
                    String url = testphoto.get(i).getPhotourl();
                    String pid = testphoto.get(i).getPid();
                    System.out.println(i);

                    // 后面加
                    System.out.println(url);
                    System.out.println(pid);

                    System.out.println("isdownloadphoto=" + isdownloadphoto);

                    if (isdownloadphoto) {
                        isdownloadphoto = false;
                        downloadsd(url, pid);

                    } else {
                        Message msg = new Message();
                        msg.what = 1;
                        Bundle bun = new Bundle();
                        bun.putString("url", url);
                        bun.putString("pid", pid);
                        msg.setData(bun);
                        savehanler1.sendMessageDelayed(msg, 300);
                    }

                }
            } else {
                System.out.println("获取头像jso数据失败，数组长度为0");

                String msg = "获取头像失败";
                String procket = "牛牛";

                // commitLog.commitLog(webviewActivity.this, msg, procket);

                // testphoto1=new ArrayList<savephotoURLBean>(testphoto);
                savephotoURLBean bean = new savephotoURLBean();
                bean.setPhotourl("");
                bean.setPid("");
                testphoto1.add(bean);
                photohandler.sendEmptyMessageDelayed(0, 100);

            }

            // photohandler.postDelayed(new Runnable() {
            //
            // @Override
            // public void run() {
            //
            // if (!getphotoistrue) {
            //
            // }
            // }
            // }, 15000);

        } catch (Exception e) {
            isdownloadphoto = true;

            System.out.println("解析头像数组失败");

            String msg = "解析头像数组失败==" + string;
            String procket = "webviewActivity catch";
            // commitLog.commitLog(webviewActivity.this, msg, procket);
            CrashReport.putUserData(webviewActivity.this, "Errorphoto",
                    e.toString());
            CrashReport.putUserData(webviewActivity.this, "Errorphotojson",
                    string);
            // testphoto1=new ArrayList<savephotoURLBean>(testphoto);
            savephotoURLBean bean = new savephotoURLBean();
            bean.setPhotourl("");
            bean.setPid("");
            testphoto1.add(bean);
            photohandler.sendEmptyMessageDelayed(0, 100);

            e.printStackTrace();
        }
    }

    private void downloadsd(final String url, final String pid) {

        if (pmutil.isnullorEmpty(url)) {

            photosize++;

            savephotoURLBean bean = new savephotoURLBean();
            bean.setPhotourl(url);
            bean.setPid(pid);
            testphoto1.add(bean);
            isdownloadphoto = true;

            if (photosize == testphoto.size()) {
                System.out.println("---" + testphoto1.toString());
                photohandler.sendEmptyMessageDelayed(0, 100);
            }

        } else {

            downloadnum = 0;

            // Object obkect = new Object();
            // synchronized (obkect) {
            // download(url, pid);
            // }

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    // try {

                    download(url, pid);
                    // } catch (Exception e) {
                    //
                    //
                    // System.out.println(e.toString());
                    // }
                }
            });

            // if (isdownloadphoto) {
            // isdownloadphoto = false;
            //
            // downloadnum = 0;
            // download(url, pid);
            // } else {
            // Message msg = new Message();
            // msg.what = 1;
            // Bundle bun = new Bundle();
            // bun.putString("url", url);
            // bun.putString("pid", pid);
            // msg.setData(bun);
            // savehanler1.sendMessageDelayed(msg, 300);
            // }
        }
    }

    private boolean isdownloadphoto = true;// 是否下载完成

    Handler savehanler1 = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Bundle bundle = msg.getData();
                    String url = bundle.getString("url");
                    String pid = bundle.getString("pid");

                    if (isdownloadphoto) {

                        downloadsd(url, pid);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        Bundle bun = new Bundle();
                        bun.putString("url", url);
                        bun.putString("pid", pid);
                        msg1.setData(bun);
                        savehanler1.sendMessageDelayed(msg1, 300);
                    }
                    break;

                default:
                    break;
            }
            super.handleMessage(msg);
        }

    };

    private void download(String url, String id) {
        downloadnum++;

        final String pid = id;
        final String photourl = url;

        sp = SpUtil.getSharePerference(this);
        final String urlpath = SpUtil.getStringSharedPerference(sp, "urlpath")
                + File.separator + Settingutil.initfile;

        System.out.println("进入下载photosize=" + photosize);
        System.out.println("photosize=" + photosize);

        photosize++;
        System.out.println("photosize=" + photosize);

        ImageCacheManager.loadImage(photourl, new ImageListener() {

            @Override
            public void onErrorResponse(VolleyError volleyError) {
                // iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_launcher));

                savephotoURLBean bean = new savephotoURLBean();
                bean.setPhotourl("");
                bean.setPid(pid);

                testphoto1.add(bean);
                isdownloadphoto = true;

                if (photosize == testphoto.size()) {
                    System.out.println(testphoto1.toString());

                    photohandler.sendEmptyMessage(0);

                }

            }

            @Override
            public void onResponse(ImageContainer container, boolean b) {
                System.out.println("%%%photosize=" + photosize);

                System.out.println("%%%container.hashCode()="
                        + container.hashCode());

                if (container.getBitmap() != null) {
                    System.out.println("&&&&&&&&&&");
                    System.out.println("***photosize=" + photosize);

                    photofile1 = new File(urlpath + File.separator + "bmp");

                    if (!photofile1.exists()) {
                        photofile1.mkdirs();
                    }

                    System.out.println("---" + photofile1.getAbsolutePath());
                    long time = System.currentTimeMillis();

                    int random = (int) (Math.random() * 9000 + 1000);
                    // 829972

                    String photname = File.separator + "bmp" + File.separator
                            + time + "" + random + ".png";

                    String photname1 = "bmp" + File.separator + time + ""
                            + random + ".png";

                    getScreenHot(container.getBitmap(), urlpath + photname);

                    savephotoURLBean bean = new savephotoURLBean();
                    bean.setPhotourl(photname1);
                    bean.setPid(pid);
                    testphoto1.add(bean);

                    isdownloadphoto = true;

                    System.out.println("photosize=" + photosize
                            + "testphoto.size()=" + testphoto.size());
                    // 已下完
                    if (photosize == testphoto.size()) {
                        System.out.println(testphoto1.toString());
                        photohandler.sendEmptyMessage(0);
                    } else {
                        isdownloadphoto = true;
                    }

                }
                // else{
                //
                // savephotoURLBean bean = new savephotoURLBean();
                // bean.setPhotourl("");
                // bean.setPid(pid);
                //
                // testphoto1.add(bean);
                // isdownloadphoto = true;
                //
                // if (photosize == testphoto.size()) {
                // System.out.println(testphoto1.toString());
                //
                // photohandler.sendEmptyMessage(0);
                //
                // }
                // }
                // iv.setImageBitmap(container.getBitmap());
            }
        });

        // // 创建一个Request
        // Request request = null;
        //
        // request = new Request.Builder().url(url).build();
        //
        // // 请求加入调度
        // okclient.newCall(request).enqueue(new Callback() {
        // @Override
        // public void onFailure(Call arg0, IOException throwable) {
        //
        // // System.out.println("下载失败");
        // // exitTitle.show(webviewActivity.this, "下载失败"+url);
        //
        // if (downloadnum >= downloadsum) {
        // photosize++;
        // savephotoURLBean bean = new savephotoURLBean();
        // bean.setPhotourl("");
        // bean.setPid(pid);
        //
        // testphoto1.add(bean);
        // isdownloadphoto = true;
        //
        // if (photosize == testphoto.size()) {
        // System.out.println(testphoto1.toString());
        //
        // photohandler.sendEmptyMessage(0);
        //
        // }
        // } else {
        // download(photourl, pid);
        // }
        //
        // throwable.printStackTrace();
        // }
        //
        // @SuppressWarnings("resource")
        // @Override
        // public void onResponse(Call arg0, Response response)
        // throws IOException {
        // System.out.println("-------------");
        // // long length = response.body().contentLength();
        //
        // if (response.code() == 200) {// 正常下载
        // System.out.println("正常下载");
        // InputStream is = null;
        // byte[] buf = new byte[2048];
        // int len = 0;
        // FileOutputStream fos = null;
        // is = response.body().byteStream();
        // photofile1 = new File(urlpath + File.separator + "bmp");
        //
        // if (!photofile1.exists()) {
        // photofile1.mkdirs();
        // }
        //
        // System.out.println(photofile1.getAbsolutePath());
        // long time = System.currentTimeMillis();
        //
        // int random = (int) (Math.random() * 9000 + 1000);
        // // 829972
        //
        // String photname = File.separator + "bmp" + File.separator
        // + time + "" + random + ".png";
        //
        // String photname1 = "bmp" + File.separator + time + ""
        // + random + ".png";
        //
        // File file2 = new File(urlpath + photname);
        //
        // fos = new FileOutputStream(file2);
        // int count = 0;
        // while ((len = is.read(buf)) != -1) {
        // fos.write(buf, 0, len);
        // count += len;
        // }
        //
        // fos.flush();
        // fos.close();
        //
        // savephotoURLBean bean = new savephotoURLBean();
        // bean.setPhotourl(photname1);
        // bean.setPid(pid);
        // testphoto1.add(bean);
        //
        // System.out.println(file2.getAbsolutePath());
        // photosize++;
        // isdownloadphoto = true;
        //
        // // 已下完
        // if (photosize == testphoto.size()) {
        // System.out.println(testphoto1.toString());
        // photohandler.sendEmptyMessage(0);
        // } else {
        // isdownloadphoto = true;
        // }
        //
        // } else {
        // System.out.println("下载失败");
        // if (downloadnum >= downloadsum) {
        // photosize++;
        // savephotoURLBean bean = new savephotoURLBean();
        // bean.setPhotourl("");
        // bean.setPid(pid);
        //
        // testphoto1.add(bean);
        // isdownloadphoto = true;
        // System.out.println("photosize=" + photosize);
        //
        // if (photosize == testphoto.size()) {
        //
        // System.out.println(testphoto1.toString());
        //
        // photohandler.sendEmptyMessage(0);
        //
        // }
        // } else {
        // System.out.println("重新下载photourl=" + photourl);
        // download(photourl, pid);
        // }
        //
        // }
        //
        // }
        // });

    }

    private Intent mService;
    /**
     * Accept and server status.
     */
    String ip;

    public void start() {
        ip = NetUtil.getLocalIPAddress();
        // 使用新的HTTP服务器替换AndServer
        NewWebServerInstance.getInstance().create(apputil.photoPort);
        
        if (NewWebServerInstance.getInstance().isRunning()) {
            System.out.println("新HTTP服务器启动成功");
        }
    }

    @PermissionSuccess(requestCode = 16)
    public void filstsucces() {

        initdate(save);
    }

    @PermissionFail(requestCode = 16)
    public void filstfail() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(
                webviewActivity.this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            // 未勾选不再提示

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("亲,当前应用缺少必要权限。不打开将无法使用");

            // 拒绝, 退出应用
            builder.setNegativeButton("退出",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            finish();

                        }
                    });

            builder.setPositiveButton("打开",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            PermissionGen.needPermission(webviewActivity.this,
                                    11,
                                    Manifest.permission.WRITE_EXTERNAL_STORAGE);
                        }
                    });
            builder.show();
            System.out.println("拒绝");
        } else {
            // 勾选不再提示
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
                showMissingPermissionDialog();
            }
        }
    }

    @SuppressWarnings("static-access")
    private void initdate(Bundle savedInstanceState) {
        inithandler();

        registerMessageReceiver();// 注册广播回调通话状态

        Shared = SpUtil.getSharePerference(webviewActivity.this);

        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID, true);

        /**
         * 微信
         */
        req = new PayReq();
        sb = new StringBuffer();
        msgApi.registerApp(Constants.APP_ID);

        initwebview(savedInstanceState);

        mDialogManager = new DialogManager(this);

        dirs = Util.GetFileAbsolutePath()
                + File.separator + "nickming_recorder_audioss";
        mAudioManager = AudioManager.getInstance(dirs);
        mAudioManager.setOnAudioStageListener(webviewActivity.this);

    }

    class mwebviewclient extends BridgeWebViewClient {
        public mwebviewclient(BridgeWebView webView) {

            super(webView);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);

        }

        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith("tel:")) {
                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);
            }
            return super.shouldOverrideUrlLoading(view, url);

        }

        @Override
        public void onReceivedHttpAuthRequest(
                WebView webview,
                com.tencent.smtt.export.external.interfaces.HttpAuthHandler httpAuthHandlerhost,
                String host, String realm) {

            boolean flag = httpAuthHandlerhost.useHttpAuthUsernamePassword();
        }
    }

    public boolean isfinsh = false;

    class mchromeClient extends WebChromeClient {

        @Override
        public void onProgressChanged(WebView arg, int arg1) {

            System.out.println(arg1);
            if (arg1 == 100) {
                service = 1;

                ObjectAnimator firstAlphaAnim = ObjectAnimator.ofFloat(
                        imageLayout, "alpha", 1.0f, 0.3f);
                firstAlphaAnim.setDuration(500);
                firstAlphaAnim.start();

                firstAlphaAnim.addListener(new AnimatorListenerAdapter() {
                    @Override
                    public void onAnimationEnd(Animator animation) {
                    // TODO Auto-generated method stub
                    super.onAnimationEnd(animation);
                    isfinsh = true;
                    imageLayout.setVisibility(View.GONE);

                    if (isfinsh) {
                        x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                //这里也是可以进行js回传的
                            }
                        });

                        //动态设置截图分享
                        String photourl = "http://" + ip + ":" + apputil.photoPort + "/testurl";

                        x5webview.callHandler("setPostUrl", photourl, new CallBackFunction() {
                            @Override
                            public void onCallBack(String data) {
                                //这里也是可以进行js回传的
                            }
                        });
                    }
                    }
                });
            }
        }

        protected void updates() {
            Map<String, String> map = new HashMap<String, String>();
            map.put("app", "youle");
            map.put("route", "agent");
            map.put("rpc", "submit_error");
            map.put("date", "appversion");
            register.PostJsonrequest(map,
            "http://120.25.60.74:1089/index.html", new Volleyinterface(
                    webviewActivity.this, Volleyinterface.mlistener,
                    Volleyinterface.mErrorLisener) {
                @Override
                public void onsuccess(String result) {
                    System.out.println("result=" + result);
                    Gson gson = new Gson();

                }

                @Override
                public void onerror(VolleyError arg0) {
                    System.out.println("arg0=" + arg0);

                }
            });
        }

        @Override
        public boolean onJsConfirm(WebView arg0, String arg1, String arg2,
                                   JsResult arg3) {
            return super.onJsConfirm(arg0, arg1, arg2, arg3);
        }

        /**
         * webview 的窗口转移
         */
        @Override
        public boolean onCreateWindow(WebView arg0, boolean arg1, boolean arg2,
                                      Message msg) {
            // TODO Auto-generated method stub

            return true;
        }

        @Override
        public boolean onJsAlert(WebView arg0, String arg1, String arg2,
                                 JsResult arg3) {
            /**
             * 这里写入你自定义的window alert
             */

            Log.i("yuanhaizhou", "setX5webview = null");
            return super.onJsAlert(null, "www.baidu.com", "aa", arg3);
        }

        /**
         * 对应js 的通知弹框 ，可以用来实现js 和 android之间的通信
         */
        @Override
        public boolean onJsPrompt(WebView arg0, String arg1, String arg2,
                                  String arg3, JsPromptResult arg4) {
            // 在这里可以判定js传过来的数据，用于调起android native 方法

            return super.onJsPrompt(arg0, arg1, arg2, arg3, arg4);
        }

        @Override
        public void onReceivedTitle(WebView arg0, final String arg1) {
            super.onReceivedTitle(arg0, arg1);
            Log.i("yuanhaizhou", "webpage title is " + arg1);

        }

    }

    RelativeLayout imageLayout;


    class myHadlerCallBack extends DefaultHandler {

        @Override
        public void handler(String data, CallBackFunction function) {

        }
    }

    @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
    private void initwebview(Bundle savedInstanceState) {

        String bugfilename = SpUtil.getStringSharedPerference(Shared,
                "bugfilename");

        if (!pmutil.isnullorEmpty(bugfilename)) {
            try {
                // uploadBug(bugfilename);
                // uploadBug1(bugfilename);
                uploadBug2(bugfilename);
            } catch (Exception e) {
                // TODO: handle exception
            }

        }

        imageLayout = (RelativeLayout) findViewById(R.id.imageLayout);

        initWebViewSettings();

        x5webview.setWebContentsDebuggingEnabled(true);

        x5webview.setWebViewClient(new mwebviewclient(x5webview));
        x5webview.setDefaultHandler(new myHadlerCallBack());
        x5webview.setWebChromeClient(new mchromeClient());

        x5webview.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                return true;
            }
        });

        if (savedInstanceState != null) {
            x5webview.restoreState(savedInstanceState);
        } else {

            String baseUrl = "file:///mnt/sdcard/test/";
            String url = SpUtil.getStringSharedPerference(Shared, "urlpath");
            url = url + File.separator + Settingutil.initfile;

            ///data/user/0/com.ts_game.xihagame/files/tsgames/com.ts_game.xihagame/1552901428056/bG7j05z4d0x7ZL03Gzy1Bzp6I8WUo7K4

            String urlswith = getAllFilename("weburl");
            System.out.println("urlswith" +urlswith);

            if(!pmutil.isnullorEmpty(urlswith)){

                System.out.println("urlswith 不为空");
                urlswith = urlswith.replaceAll("-", "/");
                urlswith="http://"+urlswith;

                x5webview.loadUrl(urlswith+"?Launchtype=0");
            }else{

                System.out.println("file://" + url + File.separator + "index.html"
                        + "?Launchtype=0");
                x5webview.loadUrl("file://" + url + File.separator + "index.html"
                        + "?Launchtype=0");

            }

            // x5webview.loadUrl("file:///android_asset/demo.html");
        }
        //x5webview.addJavascriptInterface(new settings(), "settings");

        initwebjh();

        x5webview.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int action = event.getAction();
                int x = (int) event.getX();
                int y = (int) event.getY();
                switch (action) {
                    case MotionEvent.ACTION_DOWN:

                        isDown = true;
                        changeState(STATE_RECORDING);

                        x1 = (int) event.getX();
                        y1 = (int) event.getY();
                        break;

                    case MotionEvent.ACTION_MOVE:

                        if (isRecording) {
                            // TODO
                            // 根据x，y来判断用户是否想要取消
                            if (wantToCancel(x, y, x1, y1)) {
                                changeState(STATE_WANT_TO_CANCEL);// 取消发送
                            } else {
                                changeState(STATE_RECORDING);// 继续
                            }
                        }

                        break;
                    case MotionEvent.ACTION_UP:
                        isDown = false;
                        if (isRecording) {

                            if (isautio) {
                                System.out.println("***********");
                                if (mTime < 0.8f) {
                                    System.out.println("小于0.8");
                                    mDialogManager.tooShort();
                                    mAudioManager.cancel();
                                    mhandler.sendEmptyMessageDelayed(
                                            MSG_DIALOG_DIMISS, 1300);// 持续1.3s

                                } else if (mCurrentState == STATE_RECORDING) {// 正常录制结束
                                    System.out.println("正常录制结束");
                                    mDialogManager.dimissDialog();
                                    mAudioManager.release();// release释放一个mediarecorder
                                    String amrpath = mAudioManager
                                            .getCurrentFilePath();
                                    upload(amrpath, mTime);

                                    // localityplay(amrpath);//本地播放

                                } else if (mCurrentState == STATE_WANT_TO_CANCEL) {

                                    mAudioManager.cancel();
                                    mDialogManager.dimissDialog();
                                }
                                reset();
                            } else {
                                mhandler.sendEmptyMessageDelayed(
                                        MSG_DIALOG_Audio_DIMISS, 400);// 持续1.3s
                            }
                        } else {
                            System.out.println("isautio=" + isautio);
                            mhandler.sendEmptyMessageDelayed(
                                    MSG_DIALOG_Audio_DIMISS, 400);// 持续1.3s
                        }
                        break;
                    case MotionEvent.ACTION_CANCEL:
                        if (isautio) {
                            mhandler.sendEmptyMessageDelayed(
                                    MSG_DIALOG_Audio_DIMISS, 400);// 持续1.3s
                        }
                        break;

                }

                return false;
            }
        });

        String openid = SpUtil.getStringSharedPerference(Shared, "openid");
        if (!pmutil.isnullorEmpty(openid)) {
            openid = openid.replaceAll("'", "");
            CrashReport.setUserId(openid);
        }

        strategy.setCrashHandleCallback(new CrashReport.CrashHandleCallback() {
            public Map<String, String> onCrashHandleStart(int crashType,
                                                          String errorType, String errorMessage, String errorStack) {
                LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
                String x5CrashInfo = x5webview.getCrashExtraMessage(getApplicationContext());
                map.put("x5crashInfo", x5CrashInfo);
                return map;
            }

            @Override
            public byte[] onCrashHandleStart2GetExtraDatas(int crashType,
                                                           String errorType, String errorMessage, String errorStack) {
                try {
                    return "Extra data.".getBytes("UTF-8");
                } catch (Exception e) {
                    return null;
                }
            }

        });
        CrashReport.initCrashReport(getApplicationContext(), BuglyUtil.appid, true, strategy);

        CrashReport.WebViewInterface webViewInterface = new CrashReport.WebViewInterface() {
            /**
             * 获取WebView URL.
             *
             * @return WebView URL
             */
            @Override
            public String getUrl() {
                // 下面仅为例子，请用真正逻辑代替
                return x5webview.getUrl();
            }

            /**
             * 开启JavaScript.
             *
             * @param flag
             *            true表示开启，false表示关闭
             */
            @Override
            public void setJavaScriptEnabled(boolean flag) {
                // 下面仅为例子，请用真正逻辑代替
                WebSettings webSettings = x5webview.getSettings();
                webSettings.setJavaScriptEnabled(flag);
            }

            /**
             * 加载URL.
             *
             * @param url
             *            要加载的URL
             */
            @Override
            public void loadUrl(String url) {
                // 下面仅为例子，请用真正逻辑代替
                x5webview.loadUrl(url);
            }

            /**
             * 添加JavaScript接口对象.
             *
             * @param jsInterface
             *            JavaScript接口对象
             * @param name
             *            JavaScript接口对象名称
             */
            @Override
            public void addJavascriptInterface(
                    H5JavaScriptInterface jsInterface, String name) {
                // 下面仅为例子，请用真正逻辑代替
                x5webview.addJavascriptInterface(jsInterface, name);
            }

            /**
             * 获取WebView的内容描述.
             *
             * @return WebView的内容描述.
             */
            @Override
            public CharSequence getContentDescription() {
                // 下面仅为例子，请用真正逻辑代替
                return x5webview.getContentDescription();
            }
        };
        // 调用Bugly设置JS异常捕获接口，传入创建的WebView接口对象
        CrashReport.setJavascriptMonitor(webViewInterface, true);

    }

    public void shareurl(String sharetype, String url) {
        final String type = sharetype;
        if (Wxistrue.isphotoshare) {
            Wxistrue.isphotoshare = false;

            ImageRequest imageRequest = new ImageRequest(
                    url,
                    new com.android.volley.Response.Listener<Bitmap>() {
                        @Override
                        public void onResponse(Bitmap response) {

                            File file;

                            if (Environment.getExternalStorageState()
                                    .equals(Environment.MEDIA_MOUNTED)) {
                                // sd卡存储（/mnt/sdcard/cache）
                                file = Environment
                                        .getExternalStorageDirectory();// 获取跟目录
                            } else {
                                // 没有SD卡，缓存到系统存储
                                file = Environment.getDataDirectory();
                            }
                            file = Util.GetDirectory();
                            bitmappath = file.getAbsolutePath()
                                    + File.separator + "photo.png";

                            try {
                                FileOutputStream fos = new FileOutputStream(
                                        bitmappath);
                                // bitmap.compress(CompressFormat.PNG, 100,
                                // fos);
                                // 压缩bitmap到输出流中
                                response.compress(CompressFormat.PNG, 100,
                                        fos);
                                fos.flush();
                                fos.close();
                                // Wxistrue.isshare = true;

                                Message msg = new Message();
                                Bundle data = new Bundle();
                                data.putString("bitpath", bitmappath);
                                data.putString("type", type);

                                msg.setData(data);

                                savehandler.sendMessage(msg);

                            } catch (FileNotFoundException e) {
                                throw new InvalidParameterException();
                            } catch (IOException e) {

                                e.printStackTrace();
                            }

                        }
                    }, 0, 0, Config.RGB_565,
                    new com.android.volley.Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Wxistrue.isphotoshare = true;
                        }
                    });
            volleymanager.getInstance().getmRequestQueue()
                    .add(imageRequest);
        } else {

        }
    }

    public void initwebjh() {

        //js调用Android方法  如果页面上面有多个的话，可以注册多个方法
        //submitFromWeb 要和js那边定义的一样就可以了

        x5webview.registerHandler("accreditlogin", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又进行回调的话可以在这里进行回调的
                System.out.println("jsBradge调用登录=" + data);
                Wxistrue.islogin = false;// 暂停授权登陆
                apputil.wxtype = 2;

                // 全局回调类，游戏自行实现
                /*if (!pmutil.isnullorEmpty(data)) {
                    if (data.equals("1")) {
                        //QQ登录
                        //	QQLogin();
                    } else {
                        //微信登录
                        login();
                    }
                } else {
                    login();
                }*/
                login();
            }
        });

        //图片下载
        x5webview.registerHandler("getphoto", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                System.out.println("调用图片下载"+data);
                if (!pmutil.isnullorEmpty(data)) {
                    System.out.println("isdownloadphoto=" + isdownloadphoto);
                    if (getphotoistrue) {
                        savephoto(data);
                    } else {
                        System.out.println("#############");

                        Message msg = new Message();
                        msg.what = 1;
                        Bundle bundel = new Bundle();
                        bundel.putString("photo", data);
                        msg.setData(bundel);
                        photohandler.sendMessageDelayed(msg, 200);
                    }
                } else {
                    String msg = "传递数组为空";
                    String procket = "nn";

                    // commitLog.commitLog(webviewActivity.this, msg, procket);
                }


            }
        });


        /***
         * js 调用微信分享 朋友圈或好友
         * type 1 普通分享 2截图分享 3 图片分享
         *
         * webpageUrl 分享链接地址 title 分享标题 description 分享描述
         *
         * Sharefriend  1 好友 2 朋友圈
         */

        x5webview.registerHandler("friendsSharetypeUrlToptitleDescript", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                System.out.println("调用分享=" + data);
                // 测试QQ分享
                // 显示分享面板，而不是立即执行分享
                SharePanelHelper.showSharePanel(webviewActivity.this, data);

                Gson gson = new Gson();

                bean = gson.fromJson(data, sharetypeBean.class);
                System.out.println();
                if(bean.getSharetype()==null){
                    bean.setSharetype("");
                }
                if(bean.getType()==null){
                    bean.setType("");
                }

                if(bean.getSharefriend()==null){

                    bean.setSharefriend("");
                }

                if (bean.getType().equals("3")) {
                    if(bean.getSharetype().equals("3")){
                        shareurl(bean.getSharetype(), bean.getWebpageUrl());//图片链接分享
                    }else{
                        shareurl(bean.getSharefriend(), bean.getWebpageUrl());//图片链接分享
                    }



                } else {
                    //普通分享

                    if (Wxistrue.isshare) {



                        WXEntryActivity.setshareHandler(handler);
//                        SGEntryActivity.setshareHandler(handler);

                        if(bean.getSharetype().equals("3")){
//                            if(!xlapi.isSGAppInstalled()){
//
//                                Toast.makeText(webviewActivity.this, "闲聊没有安装，请先安装闲聊", Toast.LENGTH_LONG).show();
//                            }else{
//                                xlfriend();
//                                //不能重复点击
//                                Wxistrue.isshare = false;
//                            }
                        }else{
                            if (bean.getSharefriend().equals("1")) {
                                friend();
                            } else{
                                sharefriends();
                            }
                        }
                    }else{
                        h5handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Wxistrue.isshare = true;
                            }
                        },3000);
                    }

                }


            }
        });

        //发送通知
        x5webview.registerHandler("notification", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //   Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的

                System.out.println("jsBradge调用登录=" + data);




            }
        });
        //获取系统时间
        x5webview.registerHandler("getTime", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的


                function.onCallBack(""+System.currentTimeMillis());

            }
        });

        //横竖屏切换
        x5webview.registerHandler("orientation", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的
                /**
                 * 1 为横屏 2 为竖屏
                 */
                int Orientation=1;

                try {
                    Orientation= Integer.parseInt(data);
                }catch(Exception e){

                }

                if (Orientation == 1) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }

            }
        });



        //1.普通震动    time  震动时间 单位毫秒
        x5webview.registerHandler("vibrator", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                // Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的
                long time=Long.parseLong(data);
                VibratorUtil.getInstance(webviewActivity.this).vibrate(time);

            }
        });
        //是否重复震动       repeat       -1  否   1 重复震动
        x5webview.registerHandler("repeatvibrator", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的
                int repeat= Integer.parseInt(data);
                VibratorUtil.getInstance(webviewActivity.this).repeatVibrate(
                        repeat);

            }
        });

        //取消震动
        x5webview.registerHandler("canclevibrator", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的

                VibratorUtil.getInstance(webviewActivity.this).cancle();

            }
        });
        //退出游戏
        x5webview.registerHandler("finsh", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //   Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的

                exitApp();

            }
        });

        //返回电话状态 0 无任何状态时（挂电话） 1 接起电话时 2
        x5webview.registerHandler("getphonestate", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();
                //如果js那边调用后又 进行回调的话可以在这里进行回调的
                int state=phonestate();
                function.onCallBack(""+state);


            }
        });
        //

        //长按打开音屏录音
        x5webview.registerHandler("prepareaudio", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();

                paprehandler.sendEmptyMessage(1);

            }
        });

        //播放声音audiourl  音频地址 type 1 普通  2 历史 user  用户动画位置
        x5webview.registerHandler("mediaTypeAudio", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //  Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();

                JSONObject json= null;
                try {
                    json = new JSONObject(data);
                    String audiourl=json.getString("audiourl");
                    String type=json.getString("type");
                    String user=json.getString("user");

                    System.out.println(json.toString());
                    Boolean boo = MediaFile.isAudioFileType(audiourl);

                    if (!pmutil.isnullorEmpty(audiourl)) {
                        if (boo) {
                            if (type.equals("1")) {

                                /**
                                 * 防止 播放多次调用
                                 */
                                if (!isPlayaudio) {

                                    // playautio(audiourl, user);
                                    play(audiourl, user);
                                } else {
                                    Message msg = new Message();
                                    Bundle bundel = new Bundle();
                                    bundel.putString("audiourl", audiourl);
                                    bundel.putString("user", user);
                                    msg.setData(bundel);
                                    playhandler.sendMessageDelayed(msg, 200);

                                    // playautio(audiourl, user);
                                }
                            } else {
                                if (!isPlayaudio) {
                                    // isPlaying = true;
                                    play(audiourl, user);
                                }
                            }
                        }
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

        //调用手机默认浏览器打开链接
        x5webview.registerHandler("browser", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Intent intent = new Intent();
                intent.setAction("android.intent.action.VIEW");

                Uri content_url = Uri.parse(data);
                if(BrowserUtil.isQQBrowserInstalled()){
                    intent.setClassName("com.tencent.mtt","com.tencent.mtt.MainActivity");//打开QQ浏览器
                }else{

                }
                intent.setData(content_url);
                startActivity(intent);
            }
        });

        // 主动获取电量
        x5webview.registerHandler("getbattery", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                // Toast.makeText(webviewActivity.this, data, Toast.LENGTH_LONG).show();

                IntentFilter ifilter = new IntentFilter(
                        Intent.ACTION_BATTERY_CHANGED);
                Intent batteryStatus = registerReceiver(null, ifilter);

                // 当前剩余电量
                int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL,
                        -1);
                // 电量最大值
                int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE,
                        -1);
                // 电量百分比
                float batteryPct = (level / (float) scale);


                x5webview.callHandler("getBattery", ""+batteryPct, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                        //这里也是可以进行js回传的
                    }
                });



            }
        });


        // 主动获取wifi信号
        x5webview.registerHandler("getwifiLevel", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                getWifiInfo();

                JSONObject json = new JSONObject();
                try {
                    json.put("ssidname", wifibean.getSsid());

                    json.put("signalLevel", wifibean.getSignalLevel());

                    System.out.println("---" + json.toString());
                    x5webview.callHandler("getwifiLevel", json.toString(), new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {
                            //这里也是可以进行js回传的
                        }
                    });

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        // 主动获取网络状态
        x5webview.registerHandler("getnetwork", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                String type = "1";

                boolean isnetwork = apputil
                        .isNetworkConnected(webviewActivity.this);
                if (isnetwork) {

                    boolean iswifi = apputil
                            .isNetworkAvailable(webviewActivity.this);
                    if (iswifi) {
                        type = "2";

                    } else {
                        type = "3";
                    }
                }
                function.onCallBack(type);
            }
        });

        //获取本地apk版本号是否大于网络返回版本号
        //*      code  返回   1  apk版本号>网络返回版本号
        //                    0 apk版本号<=网络返回版本号
        x5webview.registerHandler("getcompareCode", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {


                function.onCallBack(""+apputil.code);
            }
        });
        //摇一摇开始接口
        x5webview.registerHandler("startshake", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                isShake = true;
                mShakeListener.start();

            }
        });
        //摇一摇震动声音打开关闭接口
        x5webview.registerHandler("SwitchShake", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                if (data.equals("1")) {
                    apputil.Voicetype = 1;// 打開
                } else {
                    apputil.Voicetype = 0;// 關閉
                }

            }
        });
        //摇一摇震动声音打开关闭接口
        x5webview.registerHandler("stopshake", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                isShake = false;
                mShakeListener.stop();

            }
        });
        //打开扫一扫
        x5webview.registerHandler("opensaoma", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                permissionHandler.sendEmptyMessage(1);


            }
        });
        //开启定位  type 1 连续定位     2 定位1次（三秒内精度最高一次）

        x5webview.registerHandler("startlocation", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (data.equals("1")) {
                    iscontinuouslocation = true;
                } else {
                    iscontinuouslocation = false;
                }
                handellocation.sendEmptyMessage(2);


            }
        });

        // 主动获取用户定位信息 返回定位数据
        x5webview.registerHandler("getlocationinfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {


                String json = null;

                if (location != null) {
                    Gson gson = new Gson();
                    json = gson.toJson(location);
                }
                System.out.println(json);
                function.onCallBack(json);

            }
        });
        //切换子游戏
        //  webtype   2 竖屏
        //3横屏
        //Gamedirectory 目录判断游戏是否存在
        //gamedownloadurl 游戏id
        //data 数据交换

        x5webview.registerHandler("SwitchOverGameData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    System.out.println(data);
                    JSONObject obj=new JSONObject(data);
                    String webtype=obj.getString("webtype");
                    String Gamedirectory=obj.getString("Gamedirectory");
                    String gamedownloadurl=obj.getString("gamedownloadurl");
                    String data1=obj.getString("data");

                    System.out.println("webtype" + webtype + "Gamedirectory="
                            + Gamedirectory + "gamedownloadurl=" + gamedownloadurl);

                    initgame(webtype, Gamedirectory, gamedownloadurl, data1);

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

        //判断是否安装 子游戏   返回 1 安装  0未安装   data 目录名

        x5webview.registerHandler("getGameinstall", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                int i = 0;

                if (isgamedirectory(data)) {
                    i = 1;
                }
                function.onCallBack(""+i);

            }
        });
        //支付

        x5webview.registerHandler("getGameplay", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                startpay(data);

            }
        });
        //4.打开网页//数据格式 url 网页地址  title 标题 data 交互数据 orientation = 0;  横屏 1竖屏
        x5webview.registerHandler("OpenurlTitleData", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                try {
                    JSONObject obj=new JSONObject(data);
                    String url= obj.optString("url");
                    String title= obj.optString("title");
                    String data1=obj.optString("data");

                    Intent in = new Intent();

                    in.putExtra("url", url);
                    in.putExtra("title", title);
                    in.putExtra("data", data1);
                    in.setClass(webviewActivity.this, openwebActivity1.class);
                    // startActivity(in);
                    startActivityForResult(in, 1001);

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        });

        //复制接口

        x5webview.registerHandler("gameCopytext", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                ClipboardManager copy = (ClipboardManager) webviewActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                ClipData clipData = ClipData.newPlainText("TextLabel", data);
                copy.setPrimaryClip(clipData);


            }
        });

        //粘贴接口

        x5webview.registerHandler("gamepastetext", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                ClipboardManager clipboardManager = (ClipboardManager) webviewActivity.this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                String message = (String) clipboardManager.getPrimaryClip()
                        .getItemAt(0).getText();

                function.onCallBack(message);

            }
        });

        //获取市场id接口
        x5webview.registerHandler("getmarketname", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String market=getAllFilename("market");


                function.onCallBack(market);

            }
        });

        //返回获得自定义文件夹名
        x5webview.registerHandler("getothername", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String name=getAllFilename(data);


                function.onCallBack(name);

            }
        });
        //返回获得other指定文件夹
        x5webview.registerHandler("getOther", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String name=getAllFilename("other");


                function.onCallBack(name);

            }
        });
        //播放游戏声音srcIsloop

        x5webview.registerHandler("srcIsloop", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                System.out.println(data);



                try {
                    JSONObject obj=new JSONObject(data);
                    String src=obj.optString("src");
                    String isloop=obj.optString("isloop");

                    System.out.println("isloop==" + isloop);

                    Message msg = new Message();
                    System.out.println("src==" + src);
                    Bundle bun = new Bundle();
                    bun.putString("src", src);
                    bun.putString("type", ""+isloop);
                    msg.setData(bun);
                    playwav.sendMessage(msg);

                } catch (JSONException e) {
                    e.printStackTrace();
                }





            }
        });
        //语音播放开关
        x5webview.registerHandler("voicePlaying", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                if (data.equals("1")) {
                    Settingutil.voicePlaying = true;

                } else {
                    Settingutil.voicePlaying = false;
                }


            }
        });
        //打开安装应用
        x5webview.registerHandler("openApplyDownloadpath", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                String downloadpath="";
                try {
                    JSONObject obj=new JSONObject(data);
                    String packagename=obj.optString("packagename");
                    downloadpath=obj.optString("downloadpath");
                    PackageManager packageManager = getPackageManager();
                    Intent intent = new Intent();

                    intent = packageManager.getLaunchIntentForPackage(packagename);
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    Intent viewIntent = new Intent("android.intent.action.VIEW",
                            Uri.parse(downloadpath));
                    startActivity(viewIntent);
                }


            }
        });
        //当前用户加入房间或者创建房间(频道)
        x5webview.registerHandler("createRoom", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                System.out.println("调用创建加入频道--" + data);
                System.out.println("控件数量=" + containerFrame.getChildCount());
                if (data != null) {
                    Message msg = new Message();
                    msg.what = 1;
                    msg.obj = data;
                    h5handler.sendMessage(msg);
                }
            }
        });
        //2.退出房间
        x5webview.registerHandler("exitRoom", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {

                System.out.println("退出房间--" + data);

                if (data != null) {
                    Message msg = new Message();
                    msg.what = 2;
                    msg.obj = data;
                    h5handler.sendMessage(msg);
                }
            }
        });
        //3.返回当前用户视频窗口信息（左上角坐标及宽高）
        x5webview.registerHandler("getVideoinfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (data != null) {
                    System.out.println(data);
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = data;
                    h5handler.sendMessage(msg);
                }

            }
        });


        //用户点击视频是否出现悬浮框type值（默认不显示)    1显示悬浮框 2隐藏悬浮框
        x5webview.registerHandler("DragViewvideoIsshow", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                if (data.equals("1")) {
                    mDragViewvideoIsshow = true;
                } else {
                    mDragViewvideoIsshow = false;
                }

            }
        });
        //获取手机基本配置信息
        x5webview.registerHandler("getphoneInfo", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                h5handler.sendEmptyMessage(3);
            }
        });
        //获取手机通讯录 - 已注释
        x5webview.registerHandler("getAddressBook", new BridgeHandler() {
           @Override
           public void handler(String data, CallBackFunction function) {
               h5handler.sendEmptyMessage(4);
           }
        });
        //支付调用打开浏览器
        x5webview.registerHandler("paybrowser", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                Message msg = new Message();
                msg.what = 1;
                Bundle bundle = new Bundle();
                bundle.putString("browserurl", data);
                msg.setData(bundle);
                mpaybrow.sendMessage(msg);
            }
        });
        // opencamera
        x5webview.registerHandler("opencamera", new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                permissionHandler.sendEmptyMessage(2);
            }
        });


    }

    /*private void setJPushAliasandTag() {
        String unionid = SpUtil.getStringSharedPerference(Shared, "unionid");
        if (!pmutil.isnullorEmpty(unionid)) {
            unionid = unionid.replaceAll("'", "");
            JPushInterface.setAlias(this, 1, unionid);
        }
        String channel = getAllFilename("channel");
        if (!pmutil.isnullorEmpty(channel)) {
            HashSet<String> map1 = new HashSet<String>();
            map1.add(channel);

            JPushInterface.setTags(this, 1, map1);
        }
    }*/

    protected void localityplay(String amrpath) {
        Message msg = new Message();
        Bundle bundel = new Bundle();
        bundel.putString("audiourl", amrpath);
        bundel.putString("user", String.valueOf(0));
        msg.setData(bundel);
        playhandler.sendMessageDelayed(msg, 10);

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebViewSettings() {

        File file = CacheManager.getCacheFileBaseDir();
        if (file != null && file.exists() && file.isDirectory()) {
            System.out.println("----" + file.getAbsolutePath());
        }

        if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
            x5webview.getSettings().setAllowUniversalAccessFromFileURLs(true);
        }
        IX5WebViewExtension x5WebViewExtension = x5webview.getX5WebViewExtension();
        if (x5WebViewExtension != null) {
            x5WebViewExtension.setScrollBarFadingEnabled(false);
        }

        WebSettings webSetting = x5webview.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);
        // 设置WebView可触摸放大缩小
        webSetting.setSupportZoom(false);

        webSetting.setBuiltInZoomControls(false);
        // WebView双击变大，再双击后变小，当手动放大后，双击可以恢复到原始大小//设置此属性，可任意比例缩放
        webSetting.setUseWideViewPort(false);

        webSetting.setSupportMultipleWindows(false);

        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);

        webSetting.setJavaScriptEnabled(true);

        webSetting.setCacheMode(WebSettings.LOAD_NO_CACHE);// 不使用缓存，只从网络获取数据
        webSetting.setAppCacheEnabled(false);// 是否设置缓存
        webSetting.setGeolocationEnabled(true);// //设置定位的数据库路径

        webSetting.setDatabasePath(this.getDir("databases", 0).getPath());
        System.out.println(this.getDir("databases", 0).getPath());
        // 没有的话会黑屏 支持插件
        webSetting.setPluginsEnabled(true);

    }

    @Override
    protected void onStart() {
        System.out.println("onStart");
        super.onStart();
    }

    public boolean isAppOnForeground() {
        ActivityManager activityManager = (ActivityManager) getApplicationContext()
                .getSystemService(Context.ACTIVITY_SERVICE);
        String packageName = getApplicationContext().getPackageName();
        /**
         * 获取Android设备中所有正在运行的App
         */
        List<RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        if (appProcesses == null)

            return false;
        for (RunningAppProcessInfo appProcess : appProcesses) {
            // The name of the process that this object is associated with.
            if (appProcess.processName.equals(packageName)
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                return true;
            }
        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();


        Wxistrue.isshare = true;
        Wxistrue.isphotoshare = true;
        Wxistrue.islogin = true;
        if (isShake) {
            mShakeListener.start();
        }
        if (m_wklk != null) {
            m_wklk.acquire(); // 保持唤醒
        }

//        if (x5webview != null) {
//            if (isfinsh) {
//                // x5webview.loadUrl("javascript:playmediaAudio();");
//            }
//
//        }

        if (x5webview != null) {

            x5webview.onResume();
        }

        if (isForeground == false) {

            if (x5webview != null) {

//				Wxistrue.isshare = true;
//				Wxistrue.isphotoshare = true;

                service = 1;
                if (isfinsh) {
                    String appservice = "javascript:appservice(" + "'"
                            + service + "'" + ");";

//                    webviewjh(appservice);
                    System.out.println(appservice);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                                    @Override
                                    public void onCallBack(String data) {
                                        //这里也是可以进行js回传的
                                    }
                                });
                                System.out.println("appservice交互调用成功");
                            } catch (Exception e) {
                                System.out.println("appservice交互调用失败");

                            }
                        }
                    });


                }

                // x5webview.loadUrl("javascript:appservice(" + "'" + service
                // + "'" + ");");

            }

            isForeground = true;
        }
        MobclickAgent.onPageStart("webviewActivity");
        // 统计页面(仅有Activity的应用中SDK自动调用，不

        // 集成基本统计分析,初始化 Session
        UMGameAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        if (x5webview != null) {
            x5webview.onPause();
        }

        mShakeListener.stop();
        if (m_wklk != null) {
            try {
                m_wklk.release(); // 解除保持唤醒
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        super.onPause();

        /**
         * 失去焦点停止声音播放
         */
        isForeground = false;
        service = 2;
//        String appservice = "javascript:appservice(" + "'" + service + "'"
//                + ");";
//
//        webviewjh(appservice);
        x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                //这里也是可以进行js回传的
            }
        });
        MobclickAgent.onPageEnd("welcomeactivity1");
        // //集成基本统计分析, 结束 Session
        UMGameAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();

        photohandler.removeCallbacksAndMessages(null);
        mhandler.removeCallbacksAndMessages(null);

        mShakeListener.stop();

        Wxistrue.isshare = true;
        Wxistrue.isphotoshare = true;

        if (!isAppOnForeground()) {

            isForeground = false;
            service = 2;
//            String appservice = "javascript:appservice(" + "'" + service + "'"
//                    + ");";
//            webviewjh(appservice);
            x5webview.callHandler("appservice", ""+service, new CallBackFunction() {
                @Override
                public void onCallBack(String data) {
                    //这里也是可以进行js回传的
                }
            });
        }
    }

    private void jieping() {

        File file;

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // sd卡存储（/mnt/sdcard/cache）
            file = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            // 没有SD卡，缓存到系统存储
            file = Environment.getDataDirectory();
        }
        file = Util.GetDirectory();
        bitmappath = file.getAbsolutePath() + File.separator + "tes.png";
        View cv = webviewActivity.this.getWindow().getDecorView();
        getScreenHot(cv, bitmappath);

    }

    /**
     * 截取webView快照(webView加载的整个内容的大小)
     *
     * @param webView
     * @return
     */
    // public static Bitmap captureWebView1(WebView webView) {
    // webView.setDrawingCacheEnabled(true);
    // webView.buildDrawingCache();
    // Picture snapShot = webView.capturePicture();
    // Bitmap bmp = Bitmap.createBitmap(snapShot.getWidth(),
    // snapShot.getHeight(), Bitmap.Config.ARGB_8888);
    // Canvas canvas = new Canvas(bmp);
    // snapShot.draw(canvas);
    // canvas.save();
    // canvas.restore();
    // // webView.dispatchDraw(canvas);
    // webView.destroyDrawingCache();
    // return bmp;
    // }
    private Bitmap captureWebView(WebView webView) {
        Picture picture = webView.capturePicture();
        Bitmap bmp = Bitmap.createBitmap(picture.getWidth(),
                picture.getHeight(), Bitmap.Config.RGB_565);
        Canvas c = new Canvas(bmp);
        picture.draw(c);
        return bmp;
    }

    private void getbitmap(Bitmap bitmap2, String bitmappath2) {

        File file1 = new File(bitmappath2);
        try {
            file1.createNewFile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        bitmap2.compress(Bitmap.CompressFormat.PNG, 100, baos);

        int options = 100;
        while (baos.toByteArray().length / 1024 > 100 && options != 10) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();// 重置baos即清空baos
            bitmap2.compress(Bitmap.CompressFormat.PNG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;// 每次都减少10
        }

        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());// 把压缩后的数据baos存放到ByteArrayInputStream中
        // 据baos存放到ByteArrayInputStream中
        Bitmap bit = BitmapFactory.decodeStream(isBm, null, null);// 把ByteArrayInputStream数据生成图片

        System.out.println(baos.toByteArray().length);

        try {
            FileOutputStream fos = new FileOutputStream(file1);
            bit.compress(CompressFormat.PNG, 100, fos);

            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {

        } catch (IOException e) {

            e.printStackTrace();
        }

    }

    protected void friend() {
        apputil.wxtype = 1;
        Wxistrue.sharetype = 1;

        if (bean.getType().equals("1")) {

            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = bean.getWebpageUrl();
            WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = bean.getTitle();
            msg.description = bean.getDescription();
            // Toast.makeText(this, bean.getDescription(), 1).show();
            Bitmap bt = BitmapFactory.decodeResource(getResources(),
                    R.drawable.sharelogo3);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bt.compress(Bitmap.CompressFormat.PNG, 100, out);

            // Toast.makeText(webviewActivity.this, "" +
            // out.toByteArray().length,
            // 1).show();

            if (out.toByteArray().length > 32000) {
                // int a=out.toByteArray().length/30000;
                BitmapFactory.Options newOpts = new BitmapFactory.Options();
                newOpts.inJustDecodeBounds = true;

                // Toast.makeText(webviewActivity.this, "压缩", 1).show();

                BitmapFactory.decodeResource(getResources(),
                        R.drawable.sharelogo3, newOpts);

                newOpts.inJustDecodeBounds = false;
                int inSampleSize = (out.toByteArray().length / 32768 + 1) / 2 + 2;
                if (inSampleSize < 2) {
                    inSampleSize = 2;
                }

                newOpts.inSampleSize = inSampleSize;
                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.sharelogo3, newOpts);

                msg.thumbData = Util.bmpToByteArray(bitmap, true);
            } else {
                msg.thumbData = Util.bmpToByteArray(bt, true);
            }

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("webpage");
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneSession;
            api.sendReq(req);
        } else if (bean.getType().equals("2")) {
            try {

                //  photosharefriend();

            } catch (Exception e) {
                Wxistrue.isshare = true;
            }


        }
    }
    protected void xlfriend() {
        apputil.wxtype = 1;
        Wxistrue.sharetype = 3;

        if (bean.getType().equals("1")) {//pu

            //显示的图标（可选）
            Bitmap bt = BitmapFactory.decodeResource(getResources(),R.drawable.sharelogo3);



//            //初始化一个SGLinkObject对象，并设置一个分享图标
//            SGLinkObject linkObject = new SGLinkObject(bt);
//
//            //要分享的链接，必填
//            linkObject.shareUrl = bean.getWebpageUrl();
//
//            //用SGImageObject对象初始化一个SGMediaMessage对象
//            SGMediaMessage msg = new SGMediaMessage();
//            msg.mediaObject = linkObject;
//            msg.title = bean.getTitle();  //链接标题
//            msg.description = bean.getDescription();  //链接描述
//
//            //构造一个Req
//            SendMessageToSG.Req req = new SendMessageToSG.Req();
//            req.transaction = SGConstants.T_LINK;
//            req.mediaMessage = msg;
//            req.scene = SendMessageToSG.Req.SGSceneSession; //代表分享到会话列表
//
//            //调用api接口发送数据到闲聊
//            xlapi.sendReq(req);




            // Toast.makeText(webviewActivity.this, "" +
            // out.toByteArray().length,
            // 1).show();




        } else if (bean.getType().equals("2")) {
            try {

                //  photosharefriend();

            } catch (Exception e) {
                Wxistrue.isshare = true;
            }


        }
    }
    private void photoshareurlfriend(String url) {

    }



    private void xlphotosharefriend(){
        apputil.wxtype = 1;
        Wxistrue.sharetype = 3;

        Bitmap bitmap = BitmapFactory.decodeFile(bitmappath);

//        //初始化一个SGImageObject对象，设置所分享的图片内容
//        SGImageObject imageObject = new SGImageObject(bitmap);
//
//        //用SGImageObject对象初始化一个SGMediaMessage对象
//        SGMediaMessage msg = new SGMediaMessage();
//        msg.mediaObject = imageObject;
//
//        //构造一个Req
//        SendMessageToSG.Req req = new SendMessageToSG.Req();
//        req.transaction = SGConstants.T_IMAGE;
//        req.mediaMessage = msg;
//        req.scene = SendMessageToSG.Req.SGSceneSession; //代表分享到会话列表
//
//        //调用api接口发送数据到闲聊
//        xlapi.sendReq(req);

    }


    private void photosharefriend() {
        // 使用新的微信分享辅助类替换原有的直接API调用
        apputil.wxtype = 1;
        Wxistrue.sharetype = 1;
        
        // 获取微信分享工具实例
        WeChatShareUtil weChatShareUtil = WeChatShareUtil.getInstance(this);
        
        // 设置分享回调
        weChatShareUtil.setShareCallback(new WeChatShareUtil.WeChatShareCallback() {
            @Override
            public void onSuccess() {
                // 分享成功后的处理逻辑保持不变
                runOnUiThread(() -> {
                    // 可以添加成功提示或其他逻辑
                });
            }

            @Override
            public void onError(int code, String message) {
                // 分享失败后的处理逻辑
                runOnUiThread(() -> {
                    // 可以添加失败提示或其他逻辑
                });
            }

            @Override
            public void onCancel() {
                // 分享取消后的处理逻辑
                runOnUiThread(() -> {
                    // 可以添加取消提示或其他逻辑
                });
            }
        });
        
        // 使用新的分享方法分享图片到微信好友（scene = 0）
        weChatShareUtil.shareImage(this, bitmappath, 0);
    }

    protected void sharefriends() {



        apputil.wxtype = 1;

        Wxistrue.sharetype = 2;

        if (bean.getType().equals("1")) {
            WXWebpageObject webpage = new WXWebpageObject();
            webpage.webpageUrl = bean.getWebpageUrl();
            WXMediaMessage msg = new WXMediaMessage(webpage);
            msg.title = bean.getTitle();
            msg.description = bean.getDescription();
            // Toast.makeText(this, bean.getDescription(), 1).show();

            Bitmap bt = BitmapFactory.decodeResource(getResources(),
                    R.drawable.sharelogo3);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            bt.compress(Bitmap.CompressFormat.PNG, 100, out);

            // Toast.makeText(webviewActivity.this, "" +
            // out.toByteArray().length,
            // 1).show();

            if (out.toByteArray().length > 32000) {
                // int a=out.toByteArray().length/30000;
                BitmapFactory.Options newOpts = new BitmapFactory.Options();
                newOpts.inJustDecodeBounds = true;
                BitmapFactory.decodeResource(getResources(),
                        R.drawable.sharelogo3, newOpts);
                newOpts.inJustDecodeBounds = false;
                int inSampleSize = (out.toByteArray().length / 32000 + 1) / 2 + 2;
                if (inSampleSize < 2) {
                    inSampleSize = 2;
                }
                newOpts.inSampleSize = inSampleSize;

                Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
                        R.drawable.sharelogo3, newOpts);

                msg.thumbData = Util.bmpToByteArray(bitmap, true);
            } else {
                msg.thumbData = Util.bmpToByteArray(bt, true);
            }

            SendMessageToWX.Req req = new SendMessageToWX.Req();
            req.transaction = buildTransaction("webpage");
            req.message = msg;
            req.scene = SendMessageToWX.Req.WXSceneTimeline;
            api.sendReq(req);

        } else if (bean.getType().equals("2")) {
            // photosharefriends();

        }

    }

    private void photosharefriends() {
        // 使用新的微信分享辅助类替换原有的直接API调用
        apputil.wxtype = 1;
        Wxistrue.sharetype = 2;
        
        // 获取微信分享工具实例
        WeChatShareUtil weChatShareUtil = WeChatShareUtil.getInstance(this);
        
        // 设置分享回调
        weChatShareUtil.setShareCallback(new WeChatShareUtil.WeChatShareCallback() {
            @Override
            public void onSuccess() {
                // 分享成功后的处理逻辑保持不变
                runOnUiThread(() -> {
                    // 可以添加成功提示或其他逻辑
                });
            }

            @Override
            public void onError(int code, String message) {
                // 分享失败后的处理逻辑
                runOnUiThread(() -> {
                    // 可以添加失败提示或其他逻辑
                });
            }

            @Override
            public void onCancel() {
                // 分享取消后的处理逻辑
                runOnUiThread(() -> {
                    // 可以添加取消提示或其他逻辑
                });
            }
        });
        
        // 使用新的分享方法分享图片到微信朋友圈（scene = 1）
        weChatShareUtil.shareImage(this, bitmappath, 1);
        
        System.out.println(bitmappath);
    }

    // 进行质量压缩，文件大小改变 ，bitmap 不变
    public void compressBmpFromBmp(Bitmap thumb) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 100;
        thumb.compress(Bitmap.CompressFormat.PNG, options, baos);
        // Toast.makeText(MainActivity.this, "%%%%%%" +
        // baos.toByteArray().length,
        // 1).show();
        while (baos.toByteArray().length > 30000 && options != 10) {
            baos.reset(); // 清空baos
            thumb.compress(Bitmap.CompressFormat.PNG, options, baos);// 这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;
        }
        thumb.recycle();

        byte[] result = baos.toByteArray();

        try {
            baos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Toast.makeText(MainActivity.this, "&&&&&&" + result.length,
        // 1).show();
        Bitmap bit = BitmapFactory.decodeByteArray(baos.toByteArray(), 0,
                baos.toByteArray().length);
    }

    @Override
    protected void onDestroy() {

//		if(webserverInstance.getInstance().iscreatandrun()){
//			webserverInstance.getInstance().webclose();
//		}

        try {
            clearWebViewCache();
        } catch (Exception e) {
            System.out.println(e);
        }

        photohandler.removeCallbacksAndMessages(null);

        mhandler.removeCallbacksAndMessages(null);

        try {
            if (x5webview != null) {
                ViewParent parent = x5webview.getParent();
                if (parent != null) {
                    ((ViewGroup) parent).removeView(x5webview);
                }

                x5webview.stopLoading();
                x5webview.setWebChromeClient(null);
                x5webview.setWebViewClient(null);
                // 退出时调用此方法，移除绑定的服务，否则某些特定系统会报错
                x5webview.getSettings().setJavaScriptEnabled(false);

                x5webview.clearCache(true);
                x5webview.setFocusable(true); //
                x5webview.removeAllViews();
                x5webview.clearHistory();
                x5webview.clearView();
                x5webview.destroy();
                x5webview = null;

                // android.os.Process.killProcess(android.os.Process.myPid());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (mLocationClient != null) {
            mLocationClient.onDestroy();
        }

        // 停止HTTP服务器
        NewWebServerInstance.getInstance().stop();

        // Toast.makeText(this, "onDestroy", 1).show();


        System.out.println("onDestroy");
        // if (webdialog != null) {
        // webdialog.dismiss();
        // }

        unregisterReceiver(mMessageReceiver);
        unregisterReceiver(batteryReceiver);
        unregisterReceiver(WifiChangeReceiver);
        unregisterReceiver(myNetReceiver);
        screen.unregisterListener();
        if (m_wklk != null) {
            try {
                m_wklk.release(); // 解除保持唤醒
            } catch (Exception e) {
                // TODO: handle exception
            }
        }
        super.onDestroy();

    }

    private static final String TAG = openwebActivity1.class.getSimpleName();
    private static final String APP_CACAHE_DIRNAME = "/webcache";

    /**
     * 清除WebView缓存
     */
    public void clearWebViewCache() {

        //清理Webview缓存数据库
        try {
            deleteDatabase("webview.db");
            deleteDatabase("webviewCache.db");
        } catch (Exception e) {
            e.printStackTrace();
        }

//		//WebView 缓存文件
//		File appCacheDir = new File(getFilesDir().getAbsolutePath()+APP_CACAHE_DIRNAME);
//		Log.e(TAG, "appCacheDir path="+appCacheDir.getAbsolutePath());
//
//		File webviewCacheDir = new File(getCacheDir().getAbsolutePath()+"/webviewCache");
//		Log.e(TAG, "webviewCacheDir path="+webviewCacheDir.getAbsolutePath());
//		//删除webview 缓存 缓存目录
//		if(appCacheDir.exists()){
//			deleteFile(appCacheDir);
//		}

        //data/user/0/包名/Cache
        File webviewCache = new File(getCacheDir().getAbsolutePath());

        //删除webview 缓存 缓存目录

        if (webviewCache.exists()) {
            deleteFile(webviewCache);
        }

//		//删除webview 缓存目录
//		if(webviewCacheDir.exists()){
//			deleteFile(webviewCacheDir);
//		}

    }

    /**
     * 递归删除 文件/文件夹
     *
     * @param file
     */
    public void deleteFile(File file) {

        Log.i(TAG, "delete file path=" + file.getAbsolutePath());

        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
            file.delete();
        } else {
            Log.e(TAG, "delete file no exists " + file.getAbsolutePath());
        }
    }


    // 硬件加速
    private void hardwareAccelerate() {
        if (this.getPhoneSDKInt() >= 14) {
            getWindow().setFlags(0x1000000, 0x1000000);
        }
    }

    public int getPhoneSDKInt() {
        int version = 0;
        try {
            version = Integer.valueOf(android.os.Build.VERSION.SDK);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        return version;
    }

    // protected void uploadBug(String amrpath) {
    // System.out.println("上传日志地址：" + amrpath);
    // Configuration config = new
    // Configuration.Builder().zone(Zone.zone2).build();
    // UploadManager uploadManager = new UploadManager(config);
    //
    // Auth auth = Auth.create("ngN3rFW1j8dn7ZGpATKl7mreaNmp2Ei_l9AIhkIf",
    // "6VXav9eqUCORJTYvTFOeTVRonAyk4Hrs-PIZ8jmZ");
    // String auth1 = auth.uploadToken("runload");//华南
    //
    // String filename = amrpath.substring(amrpath.lastIndexOf("/") + 1);
    //
    // uploadManager.put(amrpath, filename, auth1, new UpCompletionHandler() {
    // @Override
    // public void complete(String key, ResponseInfo rinfo,
    // JSONObject response) {
    // //String s = key + ", " + rinfo + ", " + response;
    //
    // // File rile = new File(amrpath);
    // // rile.delete();
    //
    // SpUtil.setStringSharedPerference(Shared, "bugfilename", "");
    //
    // }
    //
    // }, new UploadOptions(null, null, true, null, null));
    // }

    protected void uploadBug2(final String amrpath) {
        System.out.println("上传日志地址：" + amrpath);
        UploadManager uploadManager = new UploadManager();

        Auth auth = Auth.create("ngN3rFW1j8dn7ZGpATKl7mreaNmp2Ei_l9AIhkIf",
                "6VXav9eqUCORJTYvTFOeTVRonAyk4Hrs-PIZ8jmZ");
        String auth1 = auth.uploadToken("getgamebuglog");

        String filename = amrpath.substring(amrpath.lastIndexOf("/") + 1);

        uploadManager.put(amrpath, filename, auth1, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo rinfo,
                                 JSONObject response) {
                // String s = key + ", " + rinfo + ", " + response;

                File rile = new File(amrpath);
                rile.delete();

                SpUtil.setStringSharedPerference(Shared, "bugfilename", "");

            }

        }, new UploadOptions(null, null, true, null, null));
    }

    // protected void uploadBug1(String amrpath) {
    // System.out.println("上传日志地址：" + amrpath);
    // Configuration config = new
    // Configuration.Builder().zone(Zone.zone1).build();
    // UploadManager uploadManager = new UploadManager(config);
    //
    // Auth auth = Auth.create("ngN3rFW1j8dn7ZGpATKl7mreaNmp2Ei_l9AIhkIf",
    // "6VXav9eqUCORJTYvTFOeTVRonAyk4Hrs-PIZ8jmZ");
    // String auth1 = auth.uploadToken("getbug");
    // //华北
    // String filename = amrpath.substring(amrpath.lastIndexOf("/") + 1);
    //
    // uploadManager.put(amrpath, filename, auth1, new UpCompletionHandler() {
    // @Override
    // public void complete(String key, ResponseInfo rinfo,
    // JSONObject response) {
    // //String s = key + ", " + rinfo + ", " + response;
    //
    // // File rile = new File(amrpath);
    // // rile.delete();
    //
    // SpUtil.setStringSharedPerference(Shared, "bugfilename", "");
    //
    // }
    //
    // }, new UploadOptions(null, null, true, null, null));
    // }

    protected void upload(String amrpath, final float time) {

        uploadManager = new UploadManager();

        Auth auth = Auth.create("ngN3rFW1j8dn7ZGpATKl7mreaNmp2Ei_l9AIhkIf",
                "6VXav9eqUCORJTYvTFOeTVRonAyk4Hrs-PIZ8jmZ");
        String auth1 = auth.uploadToken("gameauio");

        System.out.println("amrpath==" + amrpath);
        String filename = amrpath.substring(amrpath.lastIndexOf("/") + 1);

        uploadManager.put(amrpath, filename, auth1, new UpCompletionHandler() {
            @Override
            public void complete(String key, ResponseInfo rinfo,
                                 JSONObject response) {

                String s = key + ", " + rinfo + ", " + response;

                // Toast.makeText(MainActivity.this, s+ "\n" +
                // "http://ofc5os2op.bkt.clouddn.com/" + key, 1).show();
                System.out.println("上传成功：" + s + "\n" + "http://gameaudio.daoqi88.cn/" + key);

                // File rile = new File(amrpath);
                // rile.delete();

                SpUtil.setStringSharedPerference(Shared, "bugfilename", "");

                // 发送到前端
                // String time = rinfo.headers().get("x-qn-meta-duration");
                // if (time == null) {
                // time = "0";
                // }
                // System.out.println("time==" + time);

                // 发送到前端
                // String filepath = "http://ofc5os2op.bkt.clouddn.com/" + key;
                // String filepath = "http://ofc5os2op.bkt.clouddn.com/" + key;

                // 发送到前端
                // 发送到前端
                // String filepath = "http://gameaudio.daoqi88.cn/" + key;
                // 发送到前端
                String filepath = "http://gameaudio.daoqi88.cn/" + key;

//                String getaudiourl = "javascript:getaudiourl(" + "'" + filepath
//                        + "'" + ",'" + time + "'" + ");";
//                webviewjh(getaudiourl);

                JSONObject json = new JSONObject();

                try {
                    json.put("filepath", filepath);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    json.put("audiourl", filepath);

                    json.put("time", time);
                    x5webview.callHandler("getaudiourl", json.toString(), new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });


                }catch (Exception e){

                }




                // DownloadUrl(filepath);

            }
        }, new UploadOptions(null, null, true, null, null));
    }

    public void run(final String url) throws Exception {

        Request request = new Request.Builder().url(url).build();
        okclient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call arg0, IOException throwable) {
                throwable.printStackTrace();
            }

            @SuppressWarnings("resource")
            @Override
            public void onResponse(Call arg0, Response response)
                    throws IOException {

                if (!response.isSuccessful())
                    throw new IOException("Unexpected code " + response);
                Headers responseHeaders = response.headers();
                for (int i = 0; i < responseHeaders.size(); i++) {
                    System.out.println(responseHeaders.name(i) + ": "
                            + responseHeaders.value(i));
                }
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;

                is = response.body().byteStream();

                if (Environment.getExternalStorageState().equals(
                        Environment.MEDIA_MOUNTED)) {
                    // 获取SDCard的路径
                    destFileDir = Environment.getExternalStorageDirectory()
                            .getAbsoluteFile()
                            + File.separator
                            + "dowlod_audioss";
                    // Toast.makeText(application, sdFile.getAbsolutePath(),
                    // 1).show();
                } else {
                    destFileDir = Environment.getDataDirectory()
                            .getAbsolutePath()
                            + File.separator
                            + "dowlod_audioss";
                }
                destFileDir = Util.GetFileAbsolutePath();
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

                File file = new File(dir, getFileName(url));

                System.out.println(file.getAbsolutePath());
                fos = new FileOutputStream(file);
                while ((len = is.read(buf)) != -1) {
                    fos.write(buf, 0, len);
                }
                fos.flush();

                System.out.println(file.getAbsolutePath());
                // play(file.getAbsolutePath());

            }

        });
    }

    public void webviewjh(final String name) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                try {
                    if (x5webview != null) {
                        x5webview.loadUrl(name);
                    }

                } catch (Exception e) {
                    // Toast.makeText(webviewActivity.this, "" + e.toString(),
                    // 1)
                    // .show();
                    commitLog.commitLog(webviewActivity.this, "android登陆"
                            + name, e.toString());
                    System.out.println(e.toString());
                }
            }
        });
    }

    /**
     * @param filePathString 音频名
     * @param user           动画
     */
    protected void play(String filePathString, String user) {

        isPlayaudio = true;
        uservoice = user;
//        String call = "javascript:gameui_play_voice(" + "'" + uservoice + "'"
//                + ");";
//
//        webviewjh(call);
        x5webview.callHandler("gameui_play_voice", ""+uservoice, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });

        // Toast.makeText(this, "开始uservoice="+uservoice, 0).show();

        MediaManager.playSound(filePathString, new OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {

//                String sw = "javascript:gameui_stop_voice(" + "'" + uservoice
//                        + "'" + ");";
//                webviewjh(sw);
                if(x5webview!=null){
                    x5webview.callHandler("gameui_stop_voice", ""+uservoice, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });
                }

                isPlayaudio = false;
                uservoice = "";

                System.out.println("播放完成");

            }
        });

    }

    private String getFileName(String path) {
        int separatorIndex = path.lastIndexOf("/");

        int lastIndex = path.lastIndexOf("?");

        return (separatorIndex < 0) ? path : path.substring(separatorIndex + 1,
                lastIndex);
    }

    protected void DownloadUrl(String filepath) {

        Auth auth = Auth.create("ngN3rFW1j8dn7ZGpATKl7mreaNmp2Ei_l9AIhkIf",
                "6VXav9eqUCORJTYvTFOeTVRonAyk4Hrs-PIZ8jmZ");
        String DownloadUrl = auth.privateDownloadUrl(filepath);

        // Toast.makeText(webviewActivity.this, DownloadUrl, 1).show();
        try {
            run(DownloadUrl);

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    public void refresh_token(String refresh_token) {

        Map<String, String> map = new HashMap<String, String>();
        map.put("appid", Constants.APP_ID);
        map.put("grant_type", "refresh_token");
        map.put("refresh_token", refresh_token);

        register.StringGETrequest(map, WX_Myurl.refresh_token,
                new Volleyinterface1(this, Volleyinterface1.mlistener,
                        Volleyinterface1.mErrorLisener) {

                    @Override
                    public void onsuccess(String result) {
                        try {
                            JSONObject object = new JSONObject(result);

                            String access_token = object
                                    .optString("access_token");

                            int errcode = object.optInt("errcode");
                            Toast.makeText(webviewActivity.this,
                                    "jeef errcode==" + errcode, Toast.LENGTH_LONG).show();
                            if (errcode == 40030) {
                                login();

                            } else if (!pmutil.isnullorEmpty(access_token)) {

                                if (!pmutil.isnullorEmpty(access_token)) {
                                    SpUtil.setStringSharedPerference(Shared,
                                            "access_token", access_token);
                                }

                                int expires_in = object.optInt("expires_in");

                                String refresh_token = object
                                        .optString("refresh_token");

                                if (!pmutil.isnullorEmpty(refresh_token)) {
                                    SpUtil.setStringSharedPerference(Shared,
                                            "refresh_token", refresh_token);
                                }

                                String openid = object.optString("openid");

                                if (!pmutil.isnullorEmpty(openid)) {
                                    SpUtil.setStringSharedPerference(Shared,
                                            "openid", openid);
                                }
                                // Toast.makeText(MainActivity.this, result, 1)
                                // .show();
                                aSd = 2;
                                isaccess_token();
                            }

                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onerror(VolleyError arg0) {

                    }
                });
    }

    public void login() {
        if (!api.isWXAppInstalled()) {
            Toast.makeText(webviewActivity.this, "您还未安装微信客户端", Toast.LENGTH_SHORT).show();
            return;
        }

        //api = WXAPIFactory.createWXAPI(webviewActivity.this, Constants.APP_ID,
        //        true);
        api.registerApp(Constants.APP_ID);
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo";
        api.sendReq(req);

        WXEntryActivity.setshareHandler(handler);

    }

    public void isaccess_token() {

        final String access_token = SpUtil.getStringSharedPerference(Shared,
                "access_token");

        final String refresh_token = SpUtil.getStringSharedPerference(Shared,
                "refresh_token");

        final String openid = SpUtil
                .getStringSharedPerference(Shared, "openid");
        Map<String, String> map = new HashMap<String, String>();
        map.put("openid", openid);
        map.put("access_token", access_token);

        register.StringGETrequest(map, WX_Myurl.isaccess_token,
                new Volleyinterface1(this, Volleyinterface1.mlistener,
                        Volleyinterface1.mErrorLisener) {
                    @Override
                    public void onsuccess(String result) {
                        try {
                            JSONObject object = new JSONObject(result);
                            String errmsg = object.optString("errmsg");

                            // Toast.makeText(webviewActivity.this,
                            // "result=" + result, 1).show();
                            if (errmsg.equals("ok")) {

                                getUserInfo(access_token, openid);
                            } else {
                                // Toast.makeText(MainActivity.this,
                                // "access_token 失效重新获取", 1).show();
                                refresh_token(refresh_token);
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onerror(VolleyError arg0) {

                    }
                });
    }

    public void getuser1(String accessToken, String openId) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("openid", openId);
        map.put("access_token", accessToken);
        register.StringGETrequest(map, WX_Myurl.getwxuserinfo,
                new Volleyinterface1(this, Volleyinterface1.mlistener,
                        Volleyinterface1.mErrorLisener) {
                    @Override
                    public void onsuccess(String result) {
                        try {
                            JSONObject object = new JSONObject(result);
                            String url = object.optString("headimgurl");
                            String unionid = object.optString("unionid");
                            String openid = object.optString("openid");
                            String nickname = object.optString("nickname");
                            String sex = object.optString("sex");
                            String city = object.optString("city");
                            SpUtil.setStringSharedPerference(Shared, "unionid",
                                    unionid);
                            SpUtil.setStringSharedPerference(Shared,
                                    "headimgurl", url);
                            SpUtil.setStringSharedPerference(Shared, "openid",
                                    openid);
                            SpUtil.setStringSharedPerference(Shared,
                                    "nickname", nickname);
                            SpUtil.setStringSharedPerference(Shared, "sex", sex);
                            SpUtil.setStringSharedPerference(Shared, "city",
                                    city);
                            handler.sendEmptyMessage(1);

                        } catch (Exception e) {

                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onerror(VolleyError arg0) {

                    }
                });
    }

    private class GetPrepayIdTask extends
            AsyncTask<Void, Void, Map<String, String>> {

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onPostExecute(Map<String, String> result) {

            // Toast.makeText(MaiobdActivity.this, result.toString(), 1).show();
            if (result != null) {
                sb.append("prepay_id\n" + result.get("prepay_id") + "\n\n");

                resultunifiedorder = result;
                wxpay();
            }
            // String err=resultunifiedorder.get("err_code");
            // Toast.makeText(MaishopActivity.this, err, 1).show();
        }

        @Override
        protected void onCancelled() {
            super.onCancelled();
        }

        @Override
        protected Map<String, String> doInBackground(Void... params) {

            // String shopname=params[0];
            // String pice=params[1];
            // String ordernum=params[2];

            String url = String
                    .format("https://api.mch.weixin.qq.com/pay/unifiedorder");
            String entity = genProductArgs();
            Log.e("orion", entity);
            byte[] buf = Util.httpPost(url, entity);

            Map<String, String> xml = null;
            if (buf != null) {
                String content = new String(buf);
                Log.e("orion", content);
                xml = decodeXml(content);

            }

            return xml;
        }
    }

    public Map<String, String> decodeXml(String content) {

        try {
            Map<String, String> xml = new HashMap<String, String>();
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new StringReader(content));
            int event = parser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {

                String nodeName = parser.getName();
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:

                        break;
                    case XmlPullParser.START_TAG:

                        if ("xml".equals(nodeName) == false) {
                            // 实例化student对象
                            xml.put(nodeName, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                event = parser.next();
            }

            return xml;
        } catch (Exception e) {
            Log.e("orion", e.toString());
        }
        return null;

    }

    /**
     * 生成商户订单号
     */
    private String genNonceStr() {
        Random random = new Random();
        return MD5.getMessageDigest(String.valueOf(random.nextInt(10000))
                .getBytes());
    }

    private long genTimeStamp() {
        return System.currentTimeMillis() / 1000;
    }

    /**
     * 生成商户订单号
     */
    private String genOutTradNo(String number) {
        Random random = new Random();
        // number.getBytes()
        // String.valueOf(random.nextInt(10000)).getBytes()
        return MD5.getMessageDigest(number.getBytes());
    }

    @SuppressWarnings("deprecation")
    private String genProductArgs() {
        StringBuffer xml = new StringBuffer();
        try {
            String nonceStr = genNonceStr();
            xml.append("</xml>");
            List<NameValuePair> packageParams = new LinkedList<NameValuePair>();
            packageParams
                    .add(new BasicNameValuePair("appid", Constants.APP_ID));
            packageParams.add(new BasicNameValuePair("body", "测试哦"));
            // packageParams.add(new BasicNameValuePair("detail", "服务"));
            packageParams
                    .add(new BasicNameValuePair("mch_id", Constants.MCH_ID));
            packageParams.add(new BasicNameValuePair("nonce_str", nonceStr));// 随机字符串
            packageParams.add(new BasicNameValuePair("notify_url",
                    "http://ylyx.hxfzsw.cn/"));// 回调通知地址

            String out_trade_no = System.currentTimeMillis() + "qqq";
            packageParams.add(new BasicNameValuePair("out_trade_no",
                    out_trade_no));// 商户订单号
            packageParams.add(new BasicNameValuePair("spbill_create_ip",
                    "127.0.0.1"));// 终端IP
            packageParams.add(new BasicNameValuePair("total_fee", "1"));// 价格
            packageParams.add(new BasicNameValuePair("trade_type", "APP"));// 支付类型
            String sign = genPackageSign(packageParams);
            packageParams.add(new BasicNameValuePair("sign", sign));
            String xmlstring = toXml(packageParams);
            return xmlstring;
        } catch (Exception e) {
            //Log.e(TAG, "genProductArgs fail, ex = " + e.getMessage());
            return null;
        }
    }

    @SuppressWarnings("deprecation")
    private void genPayReq() {

        req.appId = Constants.APP_ID;// 应用id
        req.partnerId = Constants.MCH_ID;// 商户号
        req.prepayId = resultunifiedorder.get("prepay_id");// 预支付交易会话ID
        req.packageValue = "Sign=WXPay";// 扩展字段
        req.nonceStr = genNonceStr();// 随机字符串
        req.timeStamp = String.valueOf(genTimeStamp());// 时间戳

        List<NameValuePair> signParams = new LinkedList<NameValuePair>();
        signParams.add(new BasicNameValuePair("appid", req.appId));
        signParams.add(new BasicNameValuePair("noncestr", req.nonceStr));
        signParams.add(new BasicNameValuePair("package", req.packageValue));
        signParams.add(new BasicNameValuePair("partnerid", req.partnerId));
        signParams.add(new BasicNameValuePair("prepayid", req.prepayId));
        signParams.add(new BasicNameValuePair("timestamp", req.timeStamp));

        req.sign = genAppSign(signParams);// 支付签名
        sb.append("sign\n" + req.sign + "\n\n");

        Log.e("orion", signParams.toString());

    }

    /**
     * 生成下单签名
     */
    @SuppressWarnings("deprecation")
    private String genPackageSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);
        String packageSign = MD5.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();
        Log.e("orion", packageSign);
        return packageSign;
    }

    @SuppressLint("DefaultLocale")
    @SuppressWarnings("deprecation")
    private String genAppSign(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();

        for (int i = 0; i < params.size(); i++) {
            sb.append(params.get(i).getName());
            sb.append('=');
            sb.append(params.get(i).getValue());
            sb.append('&');
        }
        sb.append("key=");
        sb.append(Constants.API_KEY);

        this.sb.append("sign str\n" + sb.toString() + "\n\n");
        String appSign = MD5.getMessageDigest(sb.toString().getBytes())
                .toUpperCase();
        Log.e("orion", appSign);
        return appSign;
    }

    @SuppressWarnings("deprecation")
    private String toXml(List<NameValuePair> params) {
        StringBuilder sb = new StringBuilder();
        sb.append("<xml>");
        for (int i = 0; i < params.size(); i++) {
            sb.append("<" + params.get(i).getName() + ">");

            sb.append(params.get(i).getValue());
            sb.append("</" + params.get(i).getName() + ">");
        }
        sb.append("</xml>");

        Log.e("orion", sb.toString());
        try {
            return new String(sb.toString().getBytes(), "ISO8859-1");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

    private void sendPayReq() {
        msgApi.registerApp(Constants.APP_ID);
        msgApi.sendReq(req);
    }

    /**
     * 微信支付
     */
    private void wxpay() {
        genPayReq();
        sendPayReq();
    }

    static Map<String, mediaplayer1> map = new HashMap<String, mediaplayer1>();
    Handler playwav = new Handler() {
        public void handleMessage(Message msg) {



            Bundle bundel = msg.getData();
            String src = bundel.getString("src");
            String type = bundel.getString("type");
            String urlpath = SpUtil
                    .getStringSharedPerference(Shared, "urlpath");
            // type 0 播放一次 type 1 背景音乐（重复播放） -1 停止背景音乐
            String purl = urlpath + File.separator + Settingutil.initfile;

            String wavpath = purl + "/assets/wav/" + src;

            // if(wavpath.endsWith(".mp3")){
            // wavpath=wavpath.substring(0, wavpath.lastIndexOf("."))+".ogg";
            // }

            System.out.println("wavpath===" + wavpath);

            File file = new File(wavpath);

            // Toast.makeText(webviewActivity.this,
            // "wavpath" + wavpath + "type" + type, 0).show();

            if (file.exists() && file.isFile()) {

                int isloop = Integer.parseInt(type);
                System.out.println("isloop="+isloop);
                if (isloop > 0 || map.containsKey(src)) {

                    if (!map.containsKey(src)) {

                        mediaplayer1 me = new mediaplayer1();
                        map.put(src, me);

                        // new Thread() {
                        // public void run() {

                        me.play(wavpath, isloop, new OnCompletionListener() {

                            @Override
                            public void onCompletion(MediaPlayer mp) {

                                System.out.println("播放完成");
                            }
                        });

                        // };
                        // }.start();

                    } else {
                        mediaplayer1 me1 = map.get(src);

                        // new Thread() {
                        // public void run() {

                        me1.play(wavpath, isloop, new OnCompletionListener() {

                            @Override
                            public void onCompletion(MediaPlayer mp) {
                                System.out.println("播放完成");
                            }
                        });

                        // };
                        // }.start();

                    }// lifj732830

                } else {

                    // String path1 = getFileName1(wavpath);
                    // if(isloop==0){
                    // //SoundPool.loadSound(webviewActivity.this, path1,
                    // wavpath);
                    // System.out.println("path1="+path1+"wavpath="+wavpath);
                    // SoundPool.playSound(webviewActivity.this, path1,
                    // wavpath);
                    //
                    //
                    // }else{
                    // SoundPool.onPause(path1);//暂停
                    // }
                    System.out.println("播放音效wavpath="+wavpath+"isloop="+isloop);
                    SoundPoolUtils.playSound(wavpath, isloop);

                }

                System.out.println(wavpath);
            }

        }

        ;
    };

    public String getFileName1(String pathandname) {
        int start = pathandname.lastIndexOf("/");
        int end = pathandname.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return pathandname.substring(start + 1, end);
        } else {
            return null;
        }
    }

    Handler mpaybrow = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String browserurl = msg.getData().getString("browserurl");
                    final Intent intent = new Intent();
                    intent.setAction("android.intent.action.VIEW");
                    Uri content_url = Uri.parse(browserurl);
                    intent.setData(content_url);

                    if (!BrowserUtil.isQQBrowserInstalled()) {
                        dialogexit.show(webviewActivity.this, "建议安装QQ浏览器进行购买", new onexitlistener() {
                            @Override
                            public void paylistener() {

                            }

                            @Override
                            public void cancellistener() {
                                intent.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
                                startActivity(intent);
                            }
                        });
                    } else {
                        intent.setClassName("com.tencent.mtt", "com.tencent.mtt.MainActivity");//打开QQ浏览器

                        startActivity(intent);
                    }


                    break;

            }
        }
    };


    public void phoneInfo() {
        phoneInfoBean phoneinfobean = new phoneInfoBean();
        phoneutil util = new phoneutil(this);
        String AdresseMAC = util.getAdresseMAC();//mac 地址
        String ProvidersName = util.getProvidersName();//手机服务商信息
        String DeviceBrand = phoneutil.getDeviceBrand();//手机品牌
        String phoneIMEI = phoneutil.getIMEI(this);//手机IMEI 串号
        String phoneIMSI = phoneutil.getIMsI(this);//手机IMEI 串号
        String phoneModel = phoneutil.getSystemModel();//手机型号
        String phoneVersion = phoneutil.getSystemVersion();//手机系统版本号

        phoneinfobean.setPhoneAdresseMAC(AdresseMAC);
        phoneinfobean.setPhoneDeviceBrand(DeviceBrand);
        phoneinfobean.setPhoneIMEI(phoneIMEI);
        phoneinfobean.setPhoneIMSI(phoneIMSI);
        phoneinfobean.setPhoneModel(phoneModel);
        phoneinfobean.setPhoneProvidersName(ProvidersName);
        phoneinfobean.setPhoneVersion(phoneVersion);
        Gson gson = new Gson();
        String inf0 = gson.toJson(phoneinfobean);
        System.out.println(inf0);
//        String Level = "javascript:getphoneinfo(" + "'"
////                + inf0 + "'" + ");";
////        System.out.println(Level);
////       webviewjh(Level);
        x5webview.callHandler("getphoneinfo", inf0, new CallBackFunction() {
            @Override
            public void onCallBack(String data) {

            }
        });

    }

    TextView videotext;
    DragViewGroup mDragViewvideo;

    LinearLayout mlinearvideo;

    ImageView mvideoimg;
    ImageView mvoiceimg;
    RelativeLayout containerFrame;
    RelativeLayout mvideoimgGroup;

    public void initvideo() {

        videotext = (TextView) findViewById(R.id.videotext);
        mDragViewvideo = (DragViewGroup) findViewById(R.id.DragViewvideo);
        mlinearvideo = (LinearLayout) findViewById(R.id.linearvideo);
        mvideoimg = (ImageView) findViewById(R.id.videoimg);
        mvideoimgGroup = (RelativeLayout) findViewById(R.id.videoimgGroup);

        mvoiceimg = (ImageView) findViewById(R.id.voiceimg);

        containerFrame = (RelativeLayout) findViewById(R.id.Frame);
    }


    videoinfobean mvideoinfobean = null;

    Othervideoinfo mOthervideoinfo = null;

    String videouserinfo;
    String othervideoinfo;
    /**
     * 频道权限
     */
    public String[] vidopermission = new String[]{
            Manifest.permission.RECORD_AUDIO,
            Manifest.permission.CAMERA};

    // 注释掉通讯录权限申请相关代码
    // public String[] AddressBookpermission = new String[]{
    //        Manifest.permission.WRITE_CONTACTS};


    Handler h5handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    videouserinfo = (String) msg.obj;


                    if (!hasPermission(vidopermission)) {

                        PermissionGen.needPermission(webviewActivity.this, 111,
                                vidopermission);
                    } else {

                        Gson gson1 = new Gson();

                        try {
                            mvideoinfobean = gson1.fromJson(videouserinfo, videoinfobean.class);

                            if (!pmutil.isnullorEmpty(mvideoinfobean.getRoomid())) {
                                initAgoraEngineAndJoinChannel();
                            }

                        } catch (Exception e) {
                            // TODO: handle exception
                        }


                    }

                    break;
                case 0:

                    othervideoinfo = (String) msg.obj;
                    Gson gson1 = new Gson();

                    try {

                        mOthervideoinfo = gson1.fromJson(othervideoinfo, Othervideoinfo.class);
                        if (mOthervideoinfo != null && mOthervideoinfo.getPlayerid() != null) {
                            System.out.println("调用setupRemoteVideo()");
                            setupRemoteVideo(Integer.parseInt(mOthervideoinfo.getPlayerid()), mOthervideoinfo);

                        }

                    } catch (Exception e) {
                        // TODO: handle exception
                    }

                    break;
                case 2:

                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            exitRoom();
                        }
                    });

                    break;
                case 3:

                    phoneInfo();

                    break;
                case 4:
                    // 注释掉通讯录权限申请逻辑
                    // if (!hasPermission(AddressBookpermission)) {
                    //    PermissionGen.needPermission(webviewActivity.this, 23,
                    //            AddressBookpermission);
                    // } else {
                    //    getAddressBook();
                    // }

                    break;
                default:
                    break;
            }

        }

    };

    // 注释掉通讯录权限申请成功和失败的回调方法
    // @PermissionSuccess(requestCode = 23)
    // public void AddressBooklocation() {
    //    getAddressBook();
    // }

    // @PermissionFail(requestCode = 23)
    // public void errorAddressBook() {

    // }

    // public void getAddressBook() {
    //    String listaddress = phoneutil.getPhoneContacts(this);
    //    x5webview.callHandler("getAddressbook", listaddress, new CallBackFunction() {
    //        @Override
    //        public void onCallBack(String data) {

    //        }
    //    });
    // }

    public void initvideodata() {
        if (videomap1 != null) {
            videomap1 = null;
        }

        mlinearvideo.removeAllViews();
        mvideoimg.setImageResource(R.mipmap.a2);
        mvoiceimg.setImageResource(R.mipmap.a4);
        mDragViewvideo.setVisibility(View.GONE);
    }

    public void exitRoom() {
        try {


        } catch (Exception e) {

        }


        if (mvideoinfobean != null) {
            if (mRtcEngine != null) {


                initvideodata();

                // mRtcEngine.muteLocalVideoStream(true);
                videotext.setText(videotext.getText() + "\n 控件数量=" + containerFrame.getChildCount());
                System.out.println("控件数量=" + containerFrame.getChildCount());

                //Toast.makeText(webviewActivity.this,"控件数量="+containerFrame.getChildCount(),Toast.LENGTH_SHORT).show();
                if (containerFrame.getChildCount() > 3) {
                    int lenth = containerFrame.getChildCount() - 1;

                    //Toast.makeText(webviewActivity.this,"lenth="+lenth,Toast.LENGTH_SHORT).show();

                    for (int index = lenth; index > 2; index--) {

                        //Toast.makeText(webviewActivity.this,"index="+index,Toast.LENGTH_SHORT).show();
                        System.out.println("index=" + index);


                        try {
                            LinearLayout lineat1 = (LinearLayout) containerFrame.getChildAt(index);
                            if (lineat1 == null) {
                                Toast.makeText(webviewActivity.this, "view为空", Toast.LENGTH_SHORT).show();
                            } else {

                                lineat1.removeAllViews();
                                //lineat1.setVisibility(View.GONE);
                                containerFrame.removeView(lineat1);
                            }


                        } catch (Exception e) {
                            System.out.println("出现异常===" + e.toString());
                            Toast.makeText(webviewActivity.this, "出现异常", Toast.LENGTH_SHORT).show();
                        }

                    }

                }
                mRtcEngine.leaveChannel();


            }


        }
    }

    private void initAgoraEngineAndJoinChannel() {


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (videomap1 != null && videomap1.size() > 0) {
                    videomap1.clear();

                } else {
                    videomap1 = new HashMap<Integer, Integer>();
                }

                mymDragVideoinfoBean = new DragVideoinfoBean();

                initializeAgoraEngine();     // Tutorial Step 1
                setupVideoProfile();         // Tutorial Step 2
                setupLocalVideo();           // Tutorial Step 3
                joinChannel();               // Tutorial Step 4
            }
        });


    }


    int myuid;


    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() { // Tutorial Step 1
        @Override
        public void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed) { // Tutorial Step 5
//			runOnUiThread(new Runnable() {
//				@Override
//				public void run() {
//					System.out.println("远端视频接收解码回调otheruid=="+uid);
//
//					videotext.setText(videotext.getText()+"\n uid="+uid);
//
//					// setupRemoteVideo(uid);
//
//					String Level = "javascript:getVideoinfo(" + "'"
//							+ uid + "'"+ ");";
//
//					webviewjh(Level);
//
//				}
//			});
        }

        //onFirstRemoteVideoFrame
        // 远端视频显示回调
        @Override
        public void onFirstRemoteVideoFrame(int uid, int width, int height, int elapsed) {
            super.onFirstRemoteVideoFrame(uid, width, height, elapsed);
            System.out.println("远端视频显示回调==" + uid);
        }
        //本地视频显示回调

        @Override
        public void onFirstLocalVideoFrame(int width, int height, int elapsed) {
            super.onFirstLocalVideoFrame(width, height, elapsed);
        }

        @Override
        public void onUserOffline(final int uid, int reason) { // Tutorial Step 7
            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    System.out.println("其他用户离开频道回调" + uid);
                    onRemoteUserLeft(uid);
                }
            });
        }

        @Override
        public void onUserMuteVideo(final int uid, final boolean muted) { // Tutorial Step 10
            System.out.println("其他用户已停发已重发视频流uid==" + uid + "---" + muted);

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (!muted) {
                        //videotext.setVisibility(View.VISIBLE);
                    } else {
                        //videotext.setVisibility(View.GONE);
                    }
                    onRemoteUserVideoMuted(uid, muted);
                }
            });
        }

        @Override
        public void onUserEnableVideo(int uid, boolean enabled) {
            super.onUserEnableVideo(uid, enabled);
            //提示有其他用户启用/关闭了视频功能。
            // 关闭视频功能是指该用户只能进行语音通话，不能显示、发送自己的视频，也不能接收、显示别人的视频。

        }

        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            webviewActivity.this.myuid = uid;

            System.out.println("加入频道回调myuid=" + webviewActivity.this.myuid);

            super.onJoinChannelSuccess(channel, uid, elapsed);
        }

        @Override
        public void onRejoinChannelSuccess(String channel, int uid, int elapsed) {
            System.out.println("网络状况下重新加入频道回调myuid=" + webviewActivity.this.myuid);

        }

        @Override
        public void onUserJoined(final int uid, int elapsed) {
            System.out.println("其他用户加入频道回调" + uid);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {


                    videotext.setText(videotext.getText() + "\n uid=" + uid);

                    // setupRemoteVideo(uid);
                    x5webview.callHandler("getVideoinfo", "" + uid, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });

//                    String Level = "javascript:getVideoinfo(" + "'"
//                            + uid + "'" + ");";
//
//                    webviewjh(Level);

                }
            });
            super.onUserJoined(uid, elapsed);
        }

        @Override
        public void onLeaveChannel(RtcStats stats) {

            System.out.println("用户离开频道回调");
        }
    };

    private void onRemoteUserLeft(int uid) {
        if (mRtcEngine != null) {
            if (videomap1 != null) {
                try {
                    int uindex = videomap1.get(uid);
                    LinearLayout view = (LinearLayout) containerFrame.getChildAt(uindex);
                    System.out.println("containerFrame控件数量" + containerFrame.getChildCount());
                    System.out.println("view" + view.getChildCount());
                    view.removeAllViews();

                    //  SurfaceView surfaceView= (SurfaceView) view.getChildAt(0);

                    // view.indexOfChild(child) 获取当前view再父容器下标

                    if (view != null && view.getChildCount() > 0) {
                        System.out.println("getChildCount()" + view.getChildCount());
                        view.setVisibility(View.GONE);
                    }
                    if (view != null) {
                        containerFrame.removeView(view);
                    }

                    if (mDragViewvideo.getVisibility() == View.VISIBLE) {
                        int did = (int) mDragViewvideo.getTag();
                        if (did == uid) {
                            if (mlinearvideo.getChildCount() > 0) {
                                mlinearvideo.removeAllViews();
                            }
                            mDragViewvideo.setVisibility(View.GONE);
                        }
                    }

                } catch (Exception e) {

                }


                //RelativeGroup.removeViewAt(uindex);
            }
        }

    }


    private void onRemoteUserVideoMuted(int uid, boolean muted) {
        if (mRtcEngine != null) {
            if (videomap1 != null) {
                if (videomap1.containsKey(uid)) {
                    int uindex = videomap1.get(uid);
                    LinearLayout view = (LinearLayout) containerFrame.getChildAt(uindex);


                    // view.indexOfChild(child) 获取当前view再父容器下标

                    if (view != null && view.getChildCount() > 0) {
                        //mDragViewvideo没有显示
                        SurfaceView surfaceView = (SurfaceView) view.getChildAt(0);

                        if (!muted) {
                            surfaceView.setVisibility(View.VISIBLE);
                        } else {

                            surfaceView.setVisibility(View.GONE);
                        }
                    }
                    if (view != null) {//mDragViewvideo显示

                        if (mDragViewvideo.getVisibility() == View.VISIBLE) {


                            int did = (int) mDragViewvideo.getTag();
                            if (did == uid) {
                                if (mlinearvideo.getChildCount() > 0) {
                                    SurfaceView surfaceView = (SurfaceView) mlinearvideo.getChildAt(0);

                                    if (!muted) {
                                        surfaceView.setVisibility(View.VISIBLE);
                                    } else {
                                        surfaceView.setVisibility(View.GONE);
                                    }
                                }

//							   operatevideo1(uid);

//							   if(mlinearvideo.getChildCount()>0){
//								   mlinearvideo.removeAllViews();
//							   }
//
//							  // mDragViewvideo.setVisibility(View.GONE);
                            }
                        }

                    }

                }
                //RelativeGroup.removeViewAt(uindex);
            }
        }


    }

    Map<Integer, Integer> videomap1;//uid index父控件下标

    //Map<String, String> videomap;//uid index父控件下标

    // Tutorial Step 5
    private void setupRemoteVideo(int uid, Othervideoinfo mOthervideoinfo) {
        if (videomap1 != null) {
            System.out.println("videomap1不为空");
//			if(!videomap1.containsKey(uid)){
            if (videomap1.containsKey(uid)) {
                System.out.println("videomap1含有uid=" + uid);
            } else {
                System.out.println("videomap1不含有uid=" + uid);
            }
            initotherviiodeo(uid, mOthervideoinfo);

        } else {
            System.out.println("videomap1为空");
        }


    }

    private boolean mDragViewvideoIsshow = false;

    private void initotherviiodeo(int uid, Othervideoinfo mOthervideoinfo) {
        System.out.println("containerFram子控件数量" + containerFrame.getChildCount());

        LinearLayout autoviewGroup = new LinearLayout(this);
        int w = Stringtoint(mOthervideoinfo.getWidth());
        int h = Stringtoint(mOthervideoinfo.getHeight());
        w = getsizeh(w);
        h = getsizeh(h);
        RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(w, h);

        int left = Stringtoint(mOthervideoinfo.getLeft());
        int top = Stringtoint(mOthervideoinfo.getTop());
        left = getsizew(left);
        top = getsizeh(top);

        System.out.println("---w=" + w + "h=" + h + "left=" + left + "top=" + top);

        lay.leftMargin = left;

        lay.topMargin = top;
        autoviewGroup.setLayoutParams(lay);

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());

        surfaceView.setZOrderMediaOverlay(true);
        LinearLayout.LayoutParams itempicparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);

        surfaceView.setLayoutParams(itempicparams);

        mRtcEngine.setupRemoteVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));

        surfaceView.setTag(uid);
        autoviewGroup.setTag(uid);

        //surfaceView.setClickable(false);
        //autoviewGroup.setClickable(true);
        autoviewGroup.addView(surfaceView);
        surfaceView.setClickable(false);
        autoviewGroup.setClickable(true);

        autoviewGroup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Toast.makeText(webviewActivity.this, containerFrame.getChildCount()+"点击", Toast.LENGTH_LONG).show();
                try {
                    int uid1 = (int) v.getTag();
                    if (mDragViewvideoIsshow) {
                        updatevideo(uid1);
                    }

                } catch (Exception e) {

                }

            }
        });

//       //autoviewGroup.setBackgroundColor(Color.parseColor("#F5F5DC"));

        containerFrame.addView(autoviewGroup);

        int uindex = containerFrame.getChildCount() - 1;

        videomap1.put(uid, uindex);
        // videomap.put(String.valueOf(uid),String.valueOf(uindex));
//			}else{
//				System.out.println("videomap1含有uid="+uid);
//			}
    }


    private RtcEngine mRtcEngine;// Tutorial Step 1

    // Tutorial Step 1
    private void initializeAgoraEngine() {
        try {

            if (mRtcEngine == null) {
                mRtcEngine = RtcEngine.create(getBaseContext(), getString(R.string.agora_app_id), mRtcEventHandler);
            }

        } catch (Exception e) {
            Log.e("", Log.getStackTraceString(e));

            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
        }
    }

    // Tutorial Step 2
    private void setupVideoProfile() {
        mRtcEngine.enableVideo();
        mRtcEngine.setVideoProfile(io.agora.rtc.Constants.VIDEO_PROFILE_360P, false);
    }

    public static int getScreenWidth(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getWidth();
    }

    public static int getScreenHeight(Activity activity) {
        return activity.getWindowManager().getDefaultDisplay().getHeight();
    }

    int pmw = 0;
    int pmh = 0;

    public void getAndroiodScreenProperty() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            DisplayMetrics dm1 = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getRealMetrics(dm1);

            pmw = dm1.widthPixels;  // 屏幕宽
            pmh = dm1.heightPixels;  // 屏幕高

        } else {

            Display display = getWindowManager().getDefaultDisplay();
            DisplayMetrics dm = new DisplayMetrics();
            @SuppressWarnings("rawtypes")
            Class c;
            try {
                c = Class.forName("android.view.Display");
                @SuppressWarnings("unchecked")
                Method method = c.getMethod("getRealMetrics", DisplayMetrics.class);
                method.invoke(display, dm);
                pmh = dm.heightPixels;
                pmw = dm.widthPixels;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }


//不含虚拟状态栏宽高
//		WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
//		DisplayMetrics dm = new DisplayMetrics();
//		wm.getDefaultDisplay().getMetrics(dm);
//		int width = dm.widthPixels;         // 屏幕宽度（像素）
//
//		int height = dm.heightPixels;       // 屏幕高度（像素）
//
//		float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
//		int densityDpi = dm.densityDpi;     // 屏幕密度dpi（120 / 160 / 240）
//		// 屏幕宽度算法:屏幕宽度（像素）/屏幕密度
//		int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
//		int screenHeight = (int) (height / density);// 屏幕高度(dp)
//
//
//		pmh=height;
//		pmw=width;
//		System.out.println("屏幕宽度（像素）：" + width);
//		System.out.println("屏幕高度（像素）：" + height);
//		System.out.println("屏幕密度（0.75 / 1.0 / 1.5）：" + density);
//		System.out.println("屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
//		System.out.println("屏幕宽度（dp）：" + screenWidth);
//		System.out.println("屏幕高度（dp）：" + screenHeight);
//
//		Log.d("h_bl", "屏幕宽度（像素）：" + width);
//		Log.d("h_bl", "屏幕高度（像素）：" + height);
//		Log.d("h_bl", "屏幕密度（0.75 / 1.0 / 1.5）：" + density);
//		Log.d("h_bl", "屏幕密度dpi（120 / 160 / 240）：" + densityDpi);
//		Log.d("h_bl", "屏幕宽度（dp）：" + screenWidth);
//		Log.d("h_bl", "屏幕高度（dp）：" + screenHeight);
    }


    /**
     * @param length 长度
     * @return 返回根据比例缩放长度
     */
    public int getsizeh(int length) {
        double scale = (double) pmh / 720;
        System.out.println("scale==" + scale);
        double size = scale * length;
        System.out.println("size==" + size);
        return (int) size;
    }

    /**
     * @param length 长度
     * @return 返回根据比例缩放长度
     */
    public int getsizew(int length) {
        double scale = (double) pmw / 1280;
        System.out.println("scale==" + scale);
        double size = scale * length;
        System.out.println("size==" + size);
        return (int) size;
    }


    // Tutorial Step 3
    private void setupLocalVideo() {

        System.out.println("w=" + getScreenWidth(this) + "h=" + getScreenHeight(this));

        System.out.println(mvideoinfobean.toString());


        LinearLayout autoviewGroup = new LinearLayout(this);
        int w = Stringtoint(mvideoinfobean.getWidth());
        int h = Stringtoint(mvideoinfobean.getHeight());
        w = getsizeh(w);
        h = getsizeh(h);

        RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(w, h);
        int left = Stringtoint(mvideoinfobean.getLeft());
        int top = Stringtoint(mvideoinfobean.getTop());
        System.out.println("---w=" + w + "h=" + h + "left=" + left + "top=" + top);

        left = getsizew(left);
        top = getsizeh(top);
        lay.leftMargin = left;
        lay.topMargin = top;
        System.out.println("---w=" + w + "h=" + h + "left=" + left + "top=" + top);

        autoviewGroup.setLayoutParams(lay);

        SurfaceView surfaceView = RtcEngine.CreateRendererView(getBaseContext());
        surfaceView.setZOrderMediaOverlay(true);
        LinearLayout.LayoutParams itempicparams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);

        surfaceView.setLayoutParams(itempicparams);

        int uid = Integer.parseInt(mvideoinfobean.getPlayerid());


        autoviewGroup.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Toast.makeText(webviewActivity.this, containerFrame.getChildCount()+"点击", Toast.LENGTH_LONG).show();
                try {
                    int uid1 = (int) v.getTag();

                    if (mDragViewvideoIsshow) {
                        updatevideo(uid1);
                    }
                } catch (Exception e) {

                }

            }
        });
        autoviewGroup.setTag(uid);
        surfaceView.setTag(uid);
/**
 * 当前用户视频移动悬浮框数据初始化
 */
        mymDragVideoinfoBean.setUid(uid);
        mymDragVideoinfoBean.setVideoimg(true);
        mymDragVideoinfoBean.setVoiceimg(true);

        autoviewGroup.addView(surfaceView);
        containerFrame.addView(autoviewGroup);
        System.out.println("显示本地视频");
        int uindex1 = containerFrame.getChildCount() - 1;
        videomap1.put(uid, uindex1);
        surfaceView.setClickable(false);
        autoviewGroup.setClickable(true);
        //autoviewGroup.setFocusable(true);
        mRtcEngine.setupLocalVideo(new VideoCanvas(surfaceView, VideoCanvas.RENDER_MODE_HIDDEN, uid));
    }


    public void updatevideo(int uid) {
        if (mDragViewvideo.getTag() == null) {
            mDragViewvideo.setTag(uid);
            mvideoimg.setTag(uid);
            mvoiceimg.setTag(uid);

        } else {
            int vuid = (int) mDragViewvideo.getTag();
            mDragViewvideo.setTag(uid);

            mvideoimg.setTag(uid);
            mvoiceimg.setTag(uid);

            if (vuid == uid) {
                //mDragViewvideo显示和用户视频信息一致
                if (mDragViewvideo.getVisibility() == View.GONE) {
                    mDragViewvideo.setVisibility(View.VISIBLE);

                    System.out.println("key444444" + videomap1.get(vuid));
                    operatevideo(vuid);
                } else {
                    mDragViewvideo.setVisibility(View.GONE);
                    operatevideo1(vuid);
                }

            } else {
                //mDragViewvideo显示和用户视频信息不一致
                if (mDragViewvideo.getVisibility() == View.GONE) {
                    //mDragViewvideo必须隐藏之后再显示其他用户视频信息
                    mDragViewvideo.setVisibility(View.VISIBLE);
                    operatevideo(uid);
                } else {
                    //mDragViewvideo
                    operatevideo1(vuid);
                    operatevideo(uid);
                }
            }
        }

    }

    DragVideoinfoBean mymDragVideoinfoBean;


    public void videoimgClicked(View view) {
        if (view.getTag() != null) {
            int uid = (int) view.getTag();
            if (mymDragVideoinfoBean.getUid() == uid) {
                ImageView imageview = (ImageView) view;
                int isok = -1;
                SurfaceView surfaceView = (SurfaceView) mlinearvideo.getChildAt(0);

                if (mymDragVideoinfoBean.isVideoimg()) {

                    isok = mRtcEngine.muteLocalVideoStream(true);//暂停本地视频

                    if (isok == 0) {
                        imageview.setImageResource(R.mipmap.a1);
                        if (surfaceView != null) {
                            surfaceView.setVisibility(View.INVISIBLE);
                        }

                        mymDragVideoinfoBean.setVideoimg(false);
                    }


                } else {
                    isok = mRtcEngine.muteLocalVideoStream(false);//开始本地视频
                    if (isok == 0) {
                        if (surfaceView != null) {
                            surfaceView.setVisibility(View.VISIBLE);
                        }

                        imageview.setImageResource(R.mipmap.a2);
                        mymDragVideoinfoBean.setVideoimg(true);
                    }


                }


            }

        }


    }

    public void voiceimgClicked(View view) {
        if (view.getTag() != null) {
            int uid = (int) view.getTag();
            if (mymDragVideoinfoBean.getUid() == uid) {
                ImageView imageview = (ImageView) view;

                if (mymDragVideoinfoBean.isVoiceimg()) {
                    int isok = -1;
                    isok = mRtcEngine.muteLocalAudioStream(true);//暂停本地音频

                    if (isok == 0) {
                        imageview.setImageResource(R.mipmap.a3);

                        mymDragVideoinfoBean.setVoiceimg(false);
                    }


                } else {
                    int isok = -1;
                    isok = mRtcEngine.muteLocalAudioStream(false);//开始本地音频
                    if (isok == 0) {
                        imageview.setImageResource(R.mipmap.a4);
                        mymDragVideoinfoBean.setVoiceimg(true);
                    }

                }


            }

        }

    }

    @PermissionSuccess(requestCode = 111)
    public void videosuccess() {
        Gson gson1 = new Gson();


        try {
            mvideoinfobean = gson1.fromJson(videouserinfo, videoinfobean.class);

            if (!pmutil.isnullorEmpty(mvideoinfobean.getRoomid())) {
                initAgoraEngineAndJoinChannel();
            }

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @PermissionFail(requestCode = 111)
    public void videofail() {
        List<String> nopermission = new ArrayList<String>();
        for (int i = 0; i < vidopermission.length; i++) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    webviewActivity.this, vidopermission[i])) {
                // 未勾选不再提示
                System.out.println("拒绝");
                nopermission.add(vidopermission[i]);


            } else {
                // 勾选不再提示
                if (ContextCompat.checkSelfPermission(this, vidopermission[i]) == PackageManager.PERMISSION_DENIED) {
                    showMissingPermissionDialog();
                    break;
                }
            }
        }


        if (nopermission.size() > 0) {

            final String[] persions = new String[nopermission.size()];

            for (int i = 0; i < nopermission.size(); i++) {
                persions[i] = nopermission.get(i);
            }

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("亲,当前应用缺少必要权限。不打开将无法使用功能");

            // 拒绝, 退出应用
            builder.setNegativeButton("退出",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {


                        }
                    });

            builder.setPositiveButton("打开",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            PermissionGen.needPermission(webviewActivity.this,
                                    111, persions);
                        }
                    });
            builder.show();
        }

    }


    public void operatevideo(int uid) {


        initDragvideo(uid);

        if (videomap1 != null) {
            System.out.println("key1111111111" + videomap1.get(uid));
            int uindex = videomap1.get(uid);


            LinearLayout autoviewGroup = (LinearLayout) containerFrame.getChildAt(uindex);

            SurfaceView surfaceView = (SurfaceView) autoviewGroup.getChildAt(0);
            autoviewGroup.removeAllViews();

            if (mlinearvideo.getChildCount() > 0) {
                mlinearvideo.removeAllViews();
            }
            if (mymDragVideoinfoBean.getUid() == uid) {
                mvideoimgGroup.setVisibility(View.VISIBLE);
            } else {
                mvideoimgGroup.setVisibility(View.GONE);
            }
            surfaceView.setClickable(false);
            mlinearvideo.addView(surfaceView);
        }
    }

    /**
     * @param uid 初始化视频悬浮按钮
     */
    public void initDragvideo(int uid) {
        if (mymDragVideoinfoBean.getUid() == uid) {
            if (mymDragVideoinfoBean.isVideoimg()) {
                mvideoimg.setImageResource(R.mipmap.a2);

            } else {
                mvideoimg.setImageResource(R.mipmap.a1);
            }

            if (mymDragVideoinfoBean.isVoiceimg()) {
                mvoiceimg.setImageResource(R.mipmap.a4);
            } else {
                mvoiceimg.setImageResource(R.mipmap.a3);
            }

        }

    }

    public void operatevideo1(int uid) {
        if (videomap1 != null) {

            if (mlinearvideo.getChildCount() > 0) {

                SurfaceView surfaceView = (SurfaceView) mlinearvideo.getChildAt(0);
                mlinearvideo.removeAllViews();
                int uindex = videomap1.get(uid);
                LinearLayout autoviewGroup = (LinearLayout) containerFrame.getChildAt(uindex);


                if (autoviewGroup.getChildCount() > 0) {
                    autoviewGroup.removeAllViews();
                }

                if (mymDragVideoinfoBean.getUid() == uid) {
                    if (!mymDragVideoinfoBean.isVideoimg()) {
                        surfaceView.setVisibility(View.GONE);
                    } else {
                        surfaceView.setVisibility(View.VISIBLE);
                    }

                }
                autoviewGroup.addView(surfaceView);

            }
        }
    }

    // Tutorial Step 4
    private void joinChannel() {

        String str = mvideoinfobean.getAgentid() + mvideoinfobean.getGameid() + mvideoinfobean.getRoomid();
        //String Channel=str.substring(str.length()-64);
        String Channel = MD5(str);


        int uid = Integer.parseInt(mvideoinfobean.getPlayerid());

        mRtcEngine.joinChannel(null, Channel, "Extra Optional Data", uid); // if you do not specify the uid, we will generate the uid for you
    }


    private String MD5(String sourceStr) {
        String result = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(sourceStr.getBytes());
            byte b[] = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            result = buf.toString();
            System.out.println("MD5(" + sourceStr + ",32) = " + result);

            System.out.println("MD5(" + sourceStr + ",16) = " + buf.toString().substring(8, 24));
        } catch (NoSuchAlgorithmException e) {
            System.out.println(e);
        }

        return result;
    }

    public int Stringtoint(String d) {
        int a = (int) Double.parseDouble(d);

        return a;

    }

    @PermissionSuccess(requestCode = 19)
    public void succeslocation() {
        initlocation();
    }

    GamePayBean paybean;
    String paydata;

    public void startpay(String data2) {
        paydata = data2;

        Gson gson = new Gson();

        System.out.println(data2);

        try {

            JSONObject json = new JSONObject(data2);

            String price = (String) json.get("price");
            System.out.println(price);
            String body = json.getString("body");
            System.out.println(body);
            int typeplay = json.getInt("typeplay");
            System.out.println(typeplay);
            String type = json.getString("type");
            System.out.println(type);
            int user = json.getInt("user");
            System.out.println(user);
            paybean = new GamePayBean();
            paybean.setBody(body);
            paybean.setPrice(price);
            paybean.setType(type);
            paybean.setTypeplay(typeplay + "");
            paybean.setUser(user + "");

            WXPayEntryActivity pay = new WXPayEntryActivity();

            pay.setHandler(payhandler);
            Settingutil.iswxpay = true;

            GetPrepayIdTask getPrepayId = new GetPrepayIdTask();

            getPrepayId.execute();

        } catch (JSONException e) {

            e.printStackTrace();
        }

    }

    protected void pay(int type) {
        JSONObject obj=new JSONObject();

        try {
            obj.put("user",paybean.getUser());//用户id
            obj.put("state",type);//支付状态
            obj.put("typeplay",paybean.getTypeplay());//支付方式
            obj.put("type",paybean.getType());//支付游戏
            obj.put("data",paydata);//请求支付数据

            x5webview.callHandler("PayuserPaytypePaystate", obj.toString(), new CallBackFunction() {
                @Override
                public void onCallBack(String data) {

                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public String data = null;

    public void initgame(String webtype, String gamedirectory,
                         String gamedownloadurl, String data) {
        //int orientation = 3;  横屏
        // int orientation = 2; 竖屏
        Settingutil.initgame = gamedirectory;

        Intent in = new Intent();
        in.putExtra("orientation", webtype);
        in.putExtra("data", data);
        in.putExtra("gamedirectory", gamedirectory);
        in.putExtra("gamedownloadurl", gamedownloadurl);
        in.setClass(webviewActivity.this, NewwebviewActivity.class);
        startActivityForResult(in, 100);

        this.data = data;

    }

    // versionbean version1;

    // // 配置缺失提示
    // private void showMissingsettingDialog() {
    //
    // AlertDialog.Builder builder = new AlertDialog.Builder(this);
    // builder.setTitle("提示");
    // builder.setMessage("您好，获取配置信息失败,请重新启动应用");
    //
    // builder.setPositiveButton("退出", new DialogInterface.OnClickListener() {
    // @Override
    // public void onClick(DialogInterface dialog, int which) {
    // finish();
    // }
    // });
    //
    // AlertDialog menuDialog= builder.create();
    // //menuDialog.setCanceledOnTouchOutside(false);
    // menuDialog.setCancelable(false);
    // menuDialog.show();
    // }

    // private versionbean pullxml1(String urlpath) {
    //
    // try {
    // File file = new File(urlpath + File.separator + "version.xml");
    //
    // if (file.exists()) {
    // FileInputStream inputStream = new FileInputStream(file);
    // // 得到解析器
    // XmlPullParser parser = Xml.newPullParser();
    // // 2.设置解析的文件流
    // parser.setInput(inputStream, "utf-8");
    // // 3.得到事件类型(START_DOCUMENT,END_DOCUMENT,START_TAG, END_TAG,
    // // TEXT, etc.)
    // int type = parser.getEventType();
    // // 一直读到文档结尾
    // version1 = new versionbean();
    //
    // while (type != XmlPullParser.END_DOCUMENT) {
    //
    // switch (type) {
    // case XmlPullParser.START_TAG:
    // // 得到标签的名字
    // String tag_name = parser.getName();
    // if ("agent".equals(tag_name)) {
    //
    // String agentid = parser.getAttributeValue(null,
    // "id");
    // System.out.println("agentid=" + agentid);
    // version1.setAgentid(agentid);
    // // String id = parser.getAttributeValue(0);
    // // 得到属性值id
    // } else if ("game".equals(tag_name)) {
    // String gameid = parser
    // .getAttributeValue(null, "id");
    // System.out.println("gameid=" + gameid);
    // version1.setGameid(gameid);
    // } else if ("version".equals(tag_name)) {
    //
    // String version = parser.getAttributeValue(null,
    // "value");
    // System.out.println("version=" + version);
    // version1.setVersion(version);
    //
    // } else if ("channel".equals(tag_name)) {
    //
    // String channelid = parser.getAttributeValue(null,
    // "id");
    // version1.setChannelid(channelid);
    // }
    //
    // break;
    // default:
    // break;
    //
    // }
    // // 继续往下一个事件解析
    // type = parser.next();
    // }
    // }
    // } catch (IOException e) {
    // e.printStackTrace();
    // } catch (XmlPullParserException e) {
    // // TODO Auto-generated catch block
    // e.printStackTrace();
    // }
    // return version1;
    //
    // }

    // /**
    // * 跳转
    // *
    // * @param urlpath
    // */
    // protected void handlerend1(String urlpath) {
    //
    // Intent in = new Intent();
    // String url = urlpath + File.separator + "index.html?Launchtype=1";
    //
    // in.putExtra("urlpath", url);
    // in.putExtra("data", data);
    //
    // in.setClass(webviewActivity.this, NewwebviewActivity.class);
    // startActivityForResult(in, 100);
    //
    // }

    // protected void updatezip(String gamezip) {
    //
    // }

    // versionagentlist list1;

    private boolean isgamedirectory(String gamedirectory) {

        boolean isdirectory = false;

        /**
         * 获得解压目录
         */
        String url = SpUtil.getStringSharedPerference(Shared, "urlpath");
        File rile = new File(url);

        if (rile.exists()) {

            String[] path = rile.list();

            for (int i = 0; i < path.length; i++) {
                System.out.println(path[i]);
                if (gamedirectory.equals(path[i])) {
                    isdirectory = true;
                    break;
                }
            }

        }

        return isdirectory;

    }

    @PermissionFail(requestCode = 19)
    public void errorlocation() {
        List<String> nopermission = new ArrayList<String>();
        // String[] nopermission=null;

        for (int i = 0; i < locationpermission.length; i++) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    locationpermission[i])) {

                nopermission.add(locationpermission[i]);

                // final String permission = carpermission[i];
                // 未勾选不再提示

                System.out.println("拒绝");
            } else {
                // 勾选不再提示
                if (ContextCompat.checkSelfPermission(this,
                        locationpermission[i]) == PackageManager.PERMISSION_DENIED) {
                    // showMissingPermissionDialog();

                    break;
                }
            }
        }

        // if (nopermission.size() > 0) {
        //
        // final String[] persions = new String[nopermission.size()];
        //
        // for (int i = 0; i < nopermission.size(); i++) {
        // persions[i] = nopermission.get(i);
        // }
        //
        // AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // builder.setTitle("提示");
        // builder.setMessage("亲,当前应用缺少必要权限。不打开将无法使用");
        //
        // // 拒绝, 退出应用
        // builder.setNegativeButton("退出",
        // new DialogInterface.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        // finish();
        //
        // }
        // });
        //
        // builder.setPositiveButton("打开",
        // new DialogInterface.OnClickListener() {
        // @Override
        // public void onClick(DialogInterface dialog, int which) {
        //
        // PermissionGen.needPermission(webviewActivity.this,
        // 19, persions);
        // }
        // });
        // builder.show();
        // }

    }

    public void playautio(String audiourl, String user) {
        Message msg = new Message();
        Bundle bundel = new Bundle();
        bundel.putString("audiourl", audiourl);
        bundel.putString("user", user);
        msg.setData(bundel);
        playhandler.sendMessageDelayed(msg, 100);

    }

    public void initlocation() {

        // TODO Auto-generated method stub
        // 初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());

        // 设置定位模式
        mLocationOption.setLocationMode(AMapLocationMode.Hight_Accuracy);

        if (!iscontinuouslocation) {
            // 设置定位次数(在这里采用单次定位,true 单次定位false 连续定位)
            mLocationOption.setOnceLocation(true);
            // 设置为true，那么会返回最近3秒内定位精度最高的一次
            mLocationOption.setOnceLocationLatest(true);
        } else {
            mLocationOption.setOnceLocation(false);
            mLocationOption.setInterval(3000); // 设置连续定位时间间隔
        }

        // 设置是否返回地理信息
        mLocationOption.setNeedAddress(true);
        mLocationClient.setLocationOption(mLocationOption);
        // 设置定位监听
        mLocationClient.setLocationListener(this);
        mLocationClient.startLocation();
    }

    public void open() {

        startActivityForResult(new Intent(this, CaptureActivity.class), 100);

    }

    @PermissionSuccess(requestCode = 18)
    public void succes() {
        open();
    }

    @PermissionFail(requestCode = 18)
    public void error() {

        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.CAMERA)) {

            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("提示");
            builder.setMessage("亲,扫一扫需要打开相机权限哦");

            // 拒绝, 退出应用
            builder.setNegativeButton("不打开",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });

            builder.setPositiveButton("打开",
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            PermissionGen.needPermission(webviewActivity.this,
                                    18, camerapermission);
                        }
                    });
            builder.show();

            System.out.println("拒绝");
        } else {
            // 勾选不再提示
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.CAMERA) == PackageManager.PERMISSION_DENIED) {
                showMissingPermissionDialog();
            }
        }

    }

    public void saveBase64(String iconBase64) {
        File file;
        String bitmappath;

        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            // sd卡存储（/mnt/sdcard/cache）
            file = Environment.getExternalStorageDirectory();// 获取跟目录
        } else {
            // 没有SD卡，缓存到系统存储
            file = Environment.getDataDirectory();
        }
        file = Util.GetDirectory();
        bitmappath = file.getAbsolutePath() + File.separator + "photo.png";

        // Bitmap sd=BitmapFactory.decodeResource(getResources(),
        // R.drawable.ddd);
        // Bitmap bit1=stringtoBitmap(bitmaptoString(sd));

        Bitmap bit1 = stringtoBitmap(iconBase64);

        getScreenHot(bit1, bitmappath);

    }

    private void getScreenHot(Bitmap b1, String filePath) {
        System.out.println(filePath);
        if (b1 == null) {
            System.out.println("-----");
        }
        File file1 = new File(filePath);
        try {
            file1.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            try {

                FileOutputStream fos = new FileOutputStream(file1);
                b1.compress(CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                throw new InvalidParameterException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public Bitmap stringtoBitmap(String string) {
        // 将字符串转换成Bitmap类型
        Bitmap bitmap = null;
        try {
            byte[] bitmapArray;
            System.out.println(string);
            bitmapArray = Base64.decode(string, Base64.DEFAULT);
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
                    bitmapArray.length);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return bitmap;

    }

    public String bitmaptoString(Bitmap bitmap) {
        // 将Bitmap转换成字符串
        String string = null;
        ByteArrayOutputStream bStream = new ByteArrayOutputStream();
        bitmap.compress(CompressFormat.PNG, 100, bStream);
        byte[] bytes = bStream.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    public void photo() {
        jieping();
    }

    protected int dp2px(int dpval) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpval, getResources().getDisplayMetrics());
    }

    protected int sp2px(int spval) {

        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spval, getResources().getDisplayMetrics());

    }

    private void getScreenHot(View v1, String filePath) {

        View view1 = this.getWindow().getDecorView();
        view1.setDrawingCacheEnabled(true);
        view1.buildDrawingCache();
        Bitmap b1 = view1.getDrawingCache();

        File file1 = new File(filePath);
        try {
            file1.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            try {
                FileOutputStream fos = new FileOutputStream(file1);
                // bitmap.compress(CompressFormat.PNG, 100, fos);
                // 压缩bitmap到输出流中
                b1.compress(CompressFormat.PNG, 100, fos);
                fos.flush();
                fos.close();
            } catch (FileNotFoundException e) {
                throw new InvalidParameterException();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        view1.setDrawingCacheEnabled(false);
    }

    public static Bitmap changeColor(Bitmap bitmap) {
        if (bitmap == null) {
            return null;
        }
        int w = bitmap.getWidth();
        int h = bitmap.getHeight();
        int[] colorArray = new int[w * h];
        int n = 0;
        for (int i = 0; i < h; i++) {
            for (int j = 0; j < w; j++) {
                int color = getMixtureWhite(bitmap.getPixel(j, i));
                colorArray[n++] = color;
            }
        }
        return Bitmap.createBitmap(colorArray, w, h, Bitmap.Config.ARGB_8888);
    }

    // 获取和白色混合颜色
    private static int getMixtureWhite(int color) {
        int alpha = Color.alpha(color);
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        return Color.rgb(getSingleMixtureWhite(red, alpha),
                getSingleMixtureWhite(green, alpha),
                getSingleMixtureWhite(blue, alpha));
    }

    // 获取单色的混合值
    private static int getSingleMixtureWhite(int color, int alpha) {
        int newColor = color * alpha / 255 + 255 - alpha;
        return newColor > 255 ? 255 : newColor;
    }

    public Bitmap ratio(Bitmap image, float pixelW, float pixelH) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.PNG, 100, os);
        if (os.toByteArray().length / 1024 > 100) {// 判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();// 重置baos即清空baos
            image.compress(Bitmap.CompressFormat.PNG, 40, os);// 这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Config.ARGB_8888;
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
        // 缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;// be=1表示不缩放

        if (w > h && w > ww) {// 如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {// 如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0)
            be = 1;
        newOpts.inSampleSize = be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        // 压缩好比例大小后再进行质量压缩
        // return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
        return bitmap;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {

            case KeyEvent.KEYCODE_BACK:
                if (x5webview != null) {
                    if (x5webview.canGoBack()) {
                        x5webview.goBack();
                    } else {
                        dialogexit.show(webviewActivity.this, "确定退出",
                                new onexitlistener() {
                                    @Override
                                    public void paylistener() {

                                        exitApp();
                                    }

                                    @Override
                                    public void cancellistener() {

                                    }
                                });
                    }
                } else {
                    dialogexit.show(webviewActivity.this, "确定退出",
                            new onexitlistener() {
                                @Override
                                public void paylistener() {
                                    exitApp();
                                }

                                @Override
                                public void cancellistener() {

                                }
                            });
                }

                return true;

            default:
                break;
        }

        return super.onKeyDown(keyCode, event);
    }

    public interface OnGetUserInfoListener {
        void onGetUserInfo(String userInfo); // json字符串

        void onNetError();
    }

    static class GetUserInfoTask extends AsyncTask<Object, Void, String> {

        private OnGetUserInfoListener mListener;
        private String mUrl;

        public GetUserInfoTask(OnGetUserInfoListener listener,
                               String getUserInfoUrl) {
            mListener = listener;
            mUrl = getUserInfoUrl;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Object... params) {
            HttpURLConnection conn = null;
            BufferedReader in = null;
            StringBuilder result = new StringBuilder();

            try {
                conn = (HttpURLConnection) new URL(mUrl).openConnection();
                in = new BufferedReader(new InputStreamReader(
                        conn.getInputStream(), "UTF-8"));
                String buf;
                while ((buf = in.readLine()) != null)
                    result.append(buf);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (conn != null)
                    conn.disconnect();

                // FileUtils.close(in);
            }
            return result.toString();
        }

        @Override
        protected void onPostExecute(String s) {
            Log.d("", "onPostExecute " + s);
            mListener.onGetUserInfo(s);
        }
    }

    /**
     * 获取通话状态
     */
    public int phonestate() {
        TelephonyManager tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        int phonestate = 0;
        /**
         * 返回电话状态
         *
         * CALL_STATE_IDLE 无任何状态时 CALL_STATE_OFFHOOK 接起电话时 CALL_STATE_RINGING
         * 电话进来时
         *
         *
         */
        if (tm.getCallState() == TelephonyManager.CALL_STATE_IDLE) {
            Log.d("test", "call state idle...");
            phonestate = 0;

        } else if (tm.getCallState() == TelephonyManager.CALL_STATE_OFFHOOK) {
            Log.d("test", "call state offhook...");
            phonestate = 1;
        } else if (tm.getCallState() == TelephonyManager.CALL_STATE_RINGING) {
            Log.d("test", "call state ringing...");
            phonestate = 2;

        }
        return phonestate;
    }

    private void getUserInfo(String accessToken, String openId) {
        String url = "https://api.weixin.qq.com/sns/userinfo?"
                + "access_token=" + accessToken + "&openid=" + openId;
        GetUserInfoTask mGetUserInfoTask = new GetUserInfoTask(
                new OnGetUserInfoListener() {

                    @Override
                    public void onNetError() {

                    }

                    @Override
                    public void onGetUserInfo(String userInfo) {
                        // text.setText(userInfo);
                        // Toast.makeText(webviewActivity.this, userInfo, 1)
                        // .show();
                        JSONObject object;
                        try {
                            object = new JSONObject(userInfo);
                            String url = object.optString("headimgurl");

                            String unionid = object.optString("unionid");
                            String openid = object.optString("openid");
                            String nickname = object.optString("nickname");
                            String sex = object.optString("sex");
                            String city = object.optString("city");

                            String country = object.optString("country");
                            SpUtil.setStringSharedPerference(Shared, "country",
                                    country);

                            String province = object.optString("province");
                            SpUtil.setStringSharedPerference(Shared,
                                    "province", province);

                            SpUtil.setStringSharedPerference(Shared, "unionid",
                                    unionid);
                            SpUtil.setStringSharedPerference(Shared,
                                    "headimgurl", url);

                            SpUtil.setStringSharedPerference(Shared, "openid",
                                    openid);
                            SpUtil.setStringSharedPerference(Shared,
                                    "nickname", nickname);
                            SpUtil.setStringSharedPerference(Shared, "sex", sex);
                            SpUtil.setStringSharedPerference(Shared, "city",
                                    city);

                            handler.sendEmptyMessage(1);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                }, url);

        mGetUserInfoTask.execute();
    }

    /**
     * 退出程序
     */
    private void exitApp() {
        deleteAllFiles();

        Myapplication.getInstance().exit();

        // finish();
        // System.exit(0);
    }

    public String getAllFilename(String name) {
        System.out.println("name=" + name);

        String channelname = "";

        try {
            String[] filename = Myapplication.application.getAssets()
                    .list(name);
            System.out.println("------");

            if (filename.length > 0) {

                System.out.println("目录长度" + filename.length);

                for (int i = 0; i < filename.length; i++) {

                    System.out.println("=====" + filename[i]);

                    if (filename[i].equals("BoolTest.java")) {
                        String[] filename1 = Myapplication.application
                                .getAssets().list(
                                        name + File.separator + filename[i]);
                        System.out.println("0--" + filename1.length);
                    } else {

                        String[] name1 = Myapplication.application.getAssets()
                                .list(name + File.separator + filename[i]);
                        System.out.println("name1--" + name1.length);
                        if(name1.length>=1){
                            System.out.println("name1--" + name1[0]);
                        }

                        if (name1.length >= 0) {
                            channelname = filename[i];
                        }

                    }

                }

            } else {
                System.out.println("找不到目录");
            }

        } catch (IOException e) {

            e.printStackTrace();
        }

        return channelname;

    }

    public String getAllFilename1(String name) {

        String channelname = "";

        try {
            String[] filename = Myapplication.application.getAssets()
                    .list(name);

            if (filename.length > 0) {

                System.out.println("目录长度" + filename.length);

                for (int i = 0; i < filename.length; i++) {

                    System.out.println("=====" + filename[i]);

                    if (filename[i].equals("BoolTest.java")) {
                        String[] filename1 = Myapplication.application
                                .getAssets().list(
                                        name + File.separator + filename[i]);
                        System.out.println("0--" + filename1.length);
                    } else {

                        String[] name1 = Myapplication.application.getAssets()
                                .list(name + File.separator + filename[i]);
                        System.out.println("name1--" + name1.length);
                        System.out.println("name1--" + name1[0]);
                        if (name1.length > 0) {
                            channelname = filename[i];
                        }

                    }

                }

            }

        } catch (IOException e) {

            e.printStackTrace();
        }

        return channelname;

    }

    public void deleteAllFiles() {
        /**
         * 删除下载音频文件
         */
        if (destFileDir != null) {
            File dir1 = new File(destFileDir);

            if (dir1.exists()) {

                File[] files = new File(destFileDir).listFiles();
                for (File file : files) {
                    file.delete();
                }
            }
        }

        /**
         * 删除录音音频文件
         */
        if (dirs != null) {
            File dir = new File(dirs);
            if (dir.exists()) {
                System.out.println("-----" + dir.getAbsolutePath());
                File[] audiofiles = new File(dirs).listFiles();
                for (File file1 : audiofiles) {
                    file1.delete();
                }
            }
        }

        /**
         * 删除下载头像图片
         *
         */

        if (photofile1 != null) {

            if (photofile1.exists()) {
                System.out.println("-----" + photofile1.getAbsolutePath());
                File[] audiofiles = photofile1.listFiles();
                for (File file1 : audiofiles) {
                    file1.delete();
                }
            }
        }
        if (photofile1 != null) {

            if (photofile1.exists()) {
                System.out.println("-----" + photofile1.getAbsolutePath());
                File[] audiofiles = photofile1.listFiles();
                System.out.println("头像数量=" + audiofiles.length);
            }
        }
    }

    protected void changeState(int stateWantToCancel) {

        if (mCurrentState != stateWantToCancel) {
            mCurrentState = stateWantToCancel;
            switch (mCurrentState) {
                case STATE_NORMAL:

                    break;
                case STATE_RECORDING:

                    if (isRecording) {
                        mDialogManager.recording();
                    }
                    break;

                case STATE_WANT_TO_CANCEL:
                    mDialogManager.wantToCancel();
                    break;
            }
        }
    }

    protected boolean wantToCancel(int x, int y, int x1, int y1) {
        try {
            int mx = Math.abs(x1 - x);
            int my = Math.abs(y1 - y);

            if (mx > 100 || my > 100) {
                return true;
            }
        } catch (Exception e) {

        }

        return false;

    }

    private String buildTransaction(final String type) {

        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }

    // 获取音量大小的runnable
    private Runnable mGetVoiceLevelRunnable = new Runnable() {

        @Override
        public void run() {

            while (isRecording) {
                try {
                    Thread.sleep(100);
                    mTime += 0.1f;
                    mhandler.sendEmptyMessage(MSG_VOICE_CHANGE);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    };

    /**
     * 回复标志位以及状态
     */
    private void reset() {
        // TODO Auto-generated method stub

        if (isStopPlay) {
            isPlayaudio = false;// 可以继续播放
        }

        isStopPlay = false;

        isRecording = false;
        mTime = 0;
        isautio = false;
        changeState(STATE_NORMAL);

//        String getaudiourl = "javascript:getaudiourl(" + "'" + 0 + "'" + ",'"
//                + 0 + "'" + ");";
//
//        webviewjh(getaudiourl);

        JSONObject json = new JSONObject();
        try {
            json.put("audiourl", "");

            json.put("time", 0);
            x5webview.callHandler("getaudiourl", json.toString(), new CallBackFunction() {
                @Override
                public void onCallBack(String data) {

                }
            });


        }catch (Exception e){

        }
    }

    // 在onStart() 之后
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {

        super.onRestoreInstanceState(savedInstanceState);
    }

    // 当activity 被销毁时
    // 在onStop()之前调用, 文档中说并不保证在onPause()的之前还是之后
    // 我的试验中一般是在onPause()之后
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        System.out.println("调用onSaveInstanceState-----webviewactivity");
        //Myapplication.getInstance().exit();//退出应用

        if (x5webview != null) {

            x5webview.saveState(outState);
        }
    }

    // 在这里面发送一个handler的消息
    @Override
    public void wellPrepared() {

        System.out.println("wellPrepared");
        mhandler.sendEmptyMessage(MSG_AUDIO_PREPARED);
    }

    @Override
    public void onClick(View v) {

    }

    public MessageReceiver mMessageReceiver;

    public static String ACTION_INTENT_RECEIVER = "com.gc.broadcast.receiver";
    /**
     * 动态注册广播
     */

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();

        filter.addAction(ACTION_INTENT_RECEIVER);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            if (intent.getAction().equals(ACTION_INTENT_RECEIVER)) {
                int state = intent.getIntExtra("message", 0);

                // Toast.makeText(context, "---" + state, 1).show();
//                String user = "javascript:phonestate(" + "'" + state + "'"
//                        + ");";

                // x5webview.loadUrl("javascript:phonestate(" + "'" + state +
                // "'"
                // + ");");

                //webviewjh(user);


                x5webview.callHandler("phonestate", ""+state, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {
                        //这里也是可以进行js回传的
                    }
                });

            }
        }

    }

    @PermissionSuccess(requestCode = 101)
    public void success() {
        if (isDown) {
            try {
                prepareAudio();
            } catch (Exception e) {

            }
        }
    }

    public void prepareAudio() {

        if (isPlayaudio) {
            if (!pmutil.isnullorEmpty(uservoice)) {
                isStopPlay = true;

                MediaManager.release();
//                String gameui_stop_voice = "javascript:gameui_stop_voice("
//                        + "'" + uservoice + "'" + ");";
//                webviewjh(gameui_stop_voice);
                x5webview.callHandler("gameui_stop_voice", ""+uservoice, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                    }
                });

                uservoice = "";

            }
        }

        long backPressed = System.currentTimeMillis();
        //
        if (backPressed - lastBackPressed > QUIT_INTERVAL) {
            lastBackPressed = backPressed;
            System.out.println("准备录制");
            isautio = true;
            mAudioManager.prepareAudio();
        } else {
            lastBackPressed = backPressed;
        }
    }

    @PermissionFail(requestCode = 101)
    public void fail() {
        for (int i = 0; i < carpermission.length; i++) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(
                    webviewActivity.this, carpermission[i])) {
                // 未勾选不再提示
                System.out.println("拒绝");

            } else {
                // 勾选不再提示
                if (ContextCompat.checkSelfPermission(this, carpermission[i]) == PackageManager.PERMISSION_DENIED) {
                    showMissingPermissionDialog();
                    break;
                }
            }
        }
    }

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("当前应用缺少必要权限。请点击\"设置\"-\"权限\"-打开所需权限。");

        // 拒绝, 退出应用
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });

        builder.setPositiveButton("设置", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startAppSettings();
            }
        });

        builder.show();
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse(PACKAGE_URL_SCHEME + getPackageName()));
        startActivity(intent);
    }

    /**
     * 为子类提供一个检查权限的方法
     *
     * @param permissions
     * @return
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;

            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {

        PermissionGen.onRequestPermissionsResult(this, requestCode,
                permissions, grantResults);
    }

    class BatteryReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 判断它是否是为电量变化的Broadcast Action
            if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
                // 获取当前电量
                int level = intent.getIntExtra("level", 0);
                // 电量的总刻度
                int scale = intent.getIntExtra("scale", 100);

                // int Battery = ((level * 100) / scale);
                // Toast.makeText(webviewActivity.this, Battery, 1).show();
                float batteryPct = (level / (float) scale);
                // getBattery
                // x5webview.loadUrl("javascript:getBattery(" + "'" + batteryPct
                // + "'" + ");");


                x5webview.callHandler("getBattery", ""+batteryPct, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {

                        //这里也是可以进行js回传的
                    }
                });


//                String getBattery = "javascript:getBattery(" + "'" + batteryPct
//                        + "'" + ");";
//                if (isfinsh) {
//                    webviewjh(getBattery);
//                }

            }
        }

    }

    class WifiChangeBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println("Wifi发生变化");
            getWifiInfo();

            // x5webview.loadUrl("javascript:getwifiLevel(" + "'"
            // + wifibean.getSsid() + "'" + ",'"
            // + wifibean.getSignalLevel() + "'" + ");");



            JSONObject json = new JSONObject();
            try {
                json.put("ssidname", wifibean.getSsid());

                json.put("signalLevel", wifibean.getSignalLevel());

                System.out.println("---" + json.toString());
                x5webview.callHandler("getwifiLevel", json.toString(), new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {
                        //这里也是可以进行js回传的
                    }
                });

            } catch (JSONException e) {
                e.printStackTrace();
            }



//            if (isfinsh) {
//                String getwifiLevel = "javascript:getwifiLevel(" + "'"
//                        + wifibean.getSsid() + "'" + ",'"
//                        + wifibean.getSignalLevel() + "'" + ");";
//                webviewjh(getwifiLevel);
//            }

        }

    }

    private class MyNetReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {

            String action = intent.getAction();
            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {

                mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                netInfo = mConnectivityManager.getActiveNetworkInfo();
                int type = 1;

                if (netInfo != null && netInfo.isAvailable()) {

                    // ///////////网络连接
                    String name = netInfo.getTypeName();

                    if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        // ///WiFi网络
                        type = 2;
                    }
                    // else
                    // if(netInfo.getType()==ConnectivityManager.TYPE_ETHERNET){
                    // /////有线网络
                    //
                    // }
                    else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                        // ///////3g网络
                        type = 3;
                    }
                } else {
                    // //////网络断开
                    type = 1;
                }

                // Toast.makeText(webviewActivity.this, "类型："+type, 1).show();
                x5webview.callHandler("getnetwork", ""+type, new CallBackFunction() {
                    @Override
                    public void onCallBack(String data) {
                        //这里也是可以进行js回传的
                    }
                });



                // x5webview.loadUrl("javascript:getnetwork(" + "'" + type + "'"
                // + ");");
            }

        }

    }

    private void getWifiInfo() {

        WifiManager wifiManager = (WifiManager) this.getApplicationContext()
                .getSystemService(WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        if (wifiInfo.getBSSID() != null) {
            // wifi名称
            String ssid = wifiInfo.getSSID();
            // wifi信号强度 0-4 弱到强

            wifibean.setSsid(ssid);

            int signalLevel = WifiManager.calculateSignalLevel(
                    wifiInfo.getRssi(), 5);

            wifibean.setSignalLevel(signalLevel);
            // Toast.makeText(this, "wifi 信号强度"+signalLevel , 1).show();

            // wifi速度
            int speed = wifiInfo.getLinkSpeed();
            // wifi速度单位
            String units = WifiInfo.LINK_SPEED_UNITS;
            System.out.println("ssid=" + ssid + ",signalLevel=" + signalLevel
                    + ",speed=" + speed + ",units=" + units);
        }
    }

    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent date) {
        super.onActivityResult(requestCode, resultCode, date);
        if (requestCode == 100 && resultCode == RESULT_OK) {
            Bundle bu = date.getExtras();
            String text = bu.getString("result");

            // Toast.makeText(webviewActivity.this, text, 1).show();

//            String webjh = "javascript:getsaomaData(" + "'" + text + "'" + ");";
//            webviewjh(webjh);
            if(x5webview!=null){
                x5webview.callHandler("getsaomaData",text,new CallBackFunction(){
                    @Override
                    public void onCallBack(String data) {

                    }
                });
            }

        }

        if (requestCode == CAMERA_WITH_DATA && resultCode == RESULT_OK) {

            String userSelectPath = PHOTO_DIR + "/" + picName;
            // Toast.makeText(webviewActivity.this, userSelectPath, 1).show();
//            String webjh = "javascript:getcameraaAddress(" + "'"
//                    + userSelectPath + "'" + ");";
//            webviewjh(webjh);
            x5webview.callHandler("getcameraaAddress", userSelectPath, new CallBackFunction() {
                @Override
                public void onCallBack(String data) {

                }
            });

        }

        if (resultCode == 101) {
            Bundle bu = date.getExtras();
            String text = bu.getString("data");
//            System.out.println("网页回调给大厅=" + text);
//            String getWebdata = "javascript:getWebdata(" + "'" + text + "'"
//                    + ");";
//            webviewjh(getWebdata);

            x5webview.callHandler("getWebdata", text, new CallBackFunction() {
                @Override
                public void onCallBack(String data) {

                }
            });



        }
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {

        getuserlocationinfo(amapLocation);
    }

    MaplocationInfo location;

    private void getuserlocationinfo(AMapLocation amapLocation) {
        location = new MaplocationInfo();

        location.setLatitude(amapLocation.getLatitude());// 获取纬度

        amapLocation.getLocationType();// 获取当前定位结果来源，如网络定位结果，详见定位类型表

        location.setLongitude(amapLocation.getLongitude());// 获取经度

        amapLocation.getAccuracy();// 获取精度信息
        location.setAddress(amapLocation.getAddress());// 地址，如果option中设置isNeedAddress为false，则没有此结果，网络定位结果中会有地址信息，GPS定位不返回地址信息。
        location.setCountry(amapLocation.getCountry());// 国家信息
        location.setProvince(amapLocation.getProvince());// 省信息
        location.setCity(amapLocation.getCity());// 城市信息
        location.setDistrict(amapLocation.getDistrict());// 城区信息
        location.setStreet(amapLocation.getStreet());// 街道信息
        location.setCityCode(amapLocation.getCityCode());// 城市编码

        // amapLocation.getStreetNum();//街道门牌号信息

        // amapLocation.getAdCode();//地区编码
        // location.setAltitude(amapLocation.getAltitude());// 海拔

        amapLocation.getAoiName();// 获取当前定位点的AOI信息
        amapLocation.getBuildingId();// 获取当前室内定位的建筑物Id
        amapLocation.getFloor();// 获取当前室内定位的楼层

        handellocation.sendEmptyMessage(1);
    }

    Handler handellocation = new Handler() {
        @Override
        public void dispatchMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    Gson gson = new Gson();
                    String json = gson.toJson(location);
                    System.out.println(json);
                    // x5webview.loadUrl("javascript:getlocationinfo(" + "'" + json
                    // +
                    // "'"
                    // + ");");
//                    String getlocationinfo = "javascript:getlocationinfo(" + "'"
//                            + json + "'" + ");";
//                    webviewjh(getlocationinfo);

                    x5webview.callHandler("getlocationinfo", json, new CallBackFunction() {
                        @Override
                        public void onCallBack(String data) {

                        }
                    });
                    break;
                case 2:
                    if (!hasPermission(locationpermission)) {

                        PermissionGen.needPermission(webviewActivity.this, 19,
                                locationpermission);
                    } else {
                        initlocation();
                    }
                    break;
                default:
                    break;
            }

            super.dispatchMessage(msg);

        }
    };

    @Override
    public void resetPrepared() {
        reset();

    }
}
