package com.excelliance.open;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.os.Parcelable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.excelliance.lbui.R;
import com.excelliance.open.utils.BitmapUtils;

import java.io.Serializable;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;

@SuppressLint("NewApi")
public class PromptActivity extends BaseActivity{

    private Parcelable promptActivityParcel = null;
    private final String TAG = "PromptActivity";
    Handler handler = new Handler();
    private static final int MSG_INSTALL_DIALOG = 3;
    private static final int MSG_DOWNLOAD_DIALOG = 2;
    private static final int MSG_UPDATE_AND_NOTSPACE = 1;
    private static final int MSG_BWBX_FIRST = 4;
    private static final int MSG_CHOOSE_BY_USER = 5;
    private static final int MSG_MERGE_ERR_DIALOG = 6;
    private static final int MSG_RESTART_FOR_JJ = 7;
    private static final int MSG_LOADING_DIALOG = 8;
    private static final int MSG_SPACE_NOT_ENOUGH = 9;
    private static final int MSG_NETWORK_USELESS = 10;
    private static final int MSG_NOT_FORCE_UPDATE = 11;
    private static final int MSG_RES_PATCH = 12;
    private static final int MSG_SECID_ERR = 13;
    private static final int MSG_TARGET_SDK_VERSION_ERR = 14;
    private static final int MSG_NOTIFA_START_MAIN = 15;
    private static final int MSG_INVALID_PACKAGE = 16;
    private static final int MSG_SHOW_DOWNLOAD_SUCCESS_TOAST = 100;
    private boolean loading = false;
    @Override
    public int getLBTheme() {
        return R.style.LebianPromptTheme;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Log.d(TAG, "onCreate savedInstanceState=" + savedInstanceState);
        super.onCreate(savedInstanceState);
        if (savedInstanceState != null) {
            promptActivityParcel = savedInstanceState.getParcelable("promptActivityParcel");
        } else {
            try {
                Class clazz = BwbxUI.getClass("main.PromptActivityParcel");
                Constructor cons = clazz.getDeclaredConstructor(Parcel.class);
                cons.setAccessible(true);
                promptActivityParcel = (Parcelable) cons.newInstance((Parcel) null);
            } catch (Exception e) {
                Log.d(TAG, "no PromptActivityParcel");
                e.printStackTrace();
            }
        }
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (promptActivityParcel != null) {
            callPromptActivityParcel("init", new Class[]{Activity.class, Handler.class, Bundle.class}, new Object[]{this, handler, savedInstanceState});
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        Intent intent = getIntent();
        Log.d(TAG, "onResume" + intent.getIntExtra("dialogtype", 1));
        Serializable detail = intent.getSerializableExtra("detail");

        switch (intent.getIntExtra("dialogtype", 1)) {
            case MSG_INSTALL_DIALOG:
                Log.d(TAG, "show install dialog...");
                boolean force = intent.getBooleanExtra("forceUpdate",false);
                String apkPath = intent.getStringExtra("apkPath");
                showInstallDialog(apkPath, force);
                break;
            case MSG_DOWNLOAD_DIALOG:
                boolean isInstall = intent.getBooleanExtra("isInstall", false);
                if (isInstall) {
                    boolean forceUp = intent.getBooleanExtra("forceUpdate",false);
                    String apk = intent.getStringExtra("apkPath");
                    showInstallDialog(apk, forceUp);
                } else {
                    showDownloadedDialog(detail);
                }
                break;
            case MSG_UPDATE_AND_NOTSPACE:
                boolean dataConnection = intent.getBooleanExtra("dataConnection", false);
                boolean forceUpdate = intent.getBooleanExtra("forceUpdate",false);
                long size = intent.getLongExtra("size", (long) 0);
                long expSize = intent.getLongExtra("expsize",(long)0);
                long tSize = intent.getLongExtra("tsize",0L);
                String savePath = intent.getStringExtra("savePath");
                if (savePath != null) {
                    Boolean ad = ((Boolean) callPromptActivityParcel("alreadyDownloaded", new Class[]{Serializable.class}, new Object[]{detail}));
                    boolean alreadyDownloaded = ad == null ? false : ad.booleanValue();
                    if (!alreadyDownloaded) {
                        boolean ncKillSelf = intent.getBooleanExtra("quitKillSelf", true);
                        boolean stopOtherDl = intent.getBooleanExtra("stopOtherDl", false);
                        showUpdateDialog(detail, dataConnection, forceUpdate, size + expSize+tSize, ncKillSelf, stopOtherDl);
                    } else {
                        callPromptActivityParcel("restartGame", new Class[]{Serializable.class}, new Object[]{detail});
                    }
                } else if (forceUpdate && size > 0) {
                    Log.d(TAG, "space not enough");
                    showNotEnoughSpaceDialog(forceUpdate, size + expSize+tSize);
                } else {
                    Log.d(TAG, "space not enough in unforce");
                    finish();
                }
                break;
            case MSG_BWBX_FIRST:
                boolean zipExists = intent.getBooleanExtra("zipExists", false);
                dataConnection = intent.getBooleanExtra("dataConnection", false);
                int behavior = intent.getIntExtra("behavior", -1);//FIRST_DIALOG_BG_DOWNLOAD_NOT_NOW_BUTTON
                Log.d(TAG, "zipExists:" + zipExists + " dataConnection:" + dataConnection+"behavior:"+behavior);
                showDownloadAll(intent.getLongExtra("size", (long) 0), zipExists, dataConnection, behavior);
                break;
            case MSG_CHOOSE_BY_USER:
                int dlZipType = intent.getIntExtra("dlsZipType", 1);
                boolean lbresLater = intent.getBooleanExtra("lbresLater", false);
                showChooseBwbx(intent.getLongExtra("size", (long) 0), dlZipType, lbresLater,intent.getExtras());
                break;
            case MSG_MERGE_ERR_DIALOG:
                int mergeErrType = intent.getIntExtra("mergeErrType", 0);
                String errContent = intent.getStringExtra("errContent");
                int mainChId = intent.getIntExtra("MainChId",0);
                showMergeErrDialog(mergeErrType, errContent, mainChId);
                break;
            case MSG_RESTART_FOR_JJ:
                showRestartDialogForJJ();
                break;
            case MSG_LOADING_DIALOG:
                int type = intent.getIntExtra("type", 0);
                if (type != 1)
                    callPromptActivityParcel("loadingPackage", null, null);
                if(!loading){
                    loading = true;
                    showLoadingDialog();
                }
                break;
            case MSG_SPACE_NOT_ENOUGH:
                long requiredSize = intent.getLongExtra("requiredSize", (long) 0);
                showSpaceNotEnough(requiredSize);
                break;
            case MSG_NETWORK_USELESS:
                if ((Boolean)callPromptActivityParcel("isForeground", null, null)) {
                    showNotNetworkDialog();
                }
                break;
            case MSG_NOT_FORCE_UPDATE:
                String dealPath = intent.getStringExtra("dealpath");
                boolean fu = intent.getBooleanExtra("forceUpdate",true);
                showDloadFromWebsite(dealPath,fu);
                break;
            case MSG_RES_PATCH:
                int dlsZipType = intent.getIntExtra("dlsZipType", 1);
                Bundle bundle = intent.getExtras();
                long patchSize = bundle.getLong("rSize",0);
                boolean dataConnect = bundle.getBoolean("dataConnect",false);
                boolean forceDl = bundle.getBoolean("forceDl", false);
                showChooseResPatch(patchSize, dataConnect, dlsZipType, forceDl, bundle);
                break;
            case MSG_SECID_ERR:
                String errMsg = intent.getStringExtra("errMsg");
                showSecIdErrDialog(errMsg);
                break;
            case MSG_TARGET_SDK_VERSION_ERR:
                showTargetSdkVersionErrDialog();
                break;
            case MSG_NOTIFA_START_MAIN:
                callPromptActivityParcel("restartGame", new Class[]{Serializable.class}, new Object[]{null});
                break;
            case MSG_INVALID_PACKAGE:
                showInvalidPackageDialog();
                break;
            case MSG_SHOW_DOWNLOAD_SUCCESS_TOAST:
                showDownloadSuccessToast();
                break;
        }
        Log.e(TAG, "callPromptActivityParcel");
        callPromptActivityParcel("onResume", null, null);
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        if (promptActivityParcel != null) {
            outState.putParcelable("promptActivityParcel", promptActivityParcel);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: in resultCode= "+resultCode+",requestCode="+requestCode);
        callPromptActivityParcel("onActivityResult", new Class[]{int.class, int.class, Intent.class}, new Object[]{requestCode, resultCode, data});
    }

    @Override
    protected void onPause() {
        Log.d(TAG, "onPause");
        super.onPause();
        callPromptActivityParcel("onPause", null, null);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        callPromptActivityParcel("onDestroy", null, null);
    }

    // --------------------------------start----------------------------
    private void showDownloadedDialog(final Serializable detail) {
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setMessage(res.getString(R.string.lebian_downloaded_message_body));
        builder.setTitle(res.getString(R.string.lebian_hint));

        builder.setPositiveButton(res.getString(R.string.lebian_downloaded_current), new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("restartGame", new Class[]{Serializable.class}, new Object[]{detail});
            }
        });

        builder.setNegativeButton(res.getString(R.string.lebian_downloaded_next), new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
            }
        });

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }


    private void showInstallDialog(final String apkPath, final boolean forceUpdate) {
        Log.d(TAG, "showInstallDialog: in");
        String packageName = getPackageName();
        Dialog installDialog = null;
//        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        int resId = forceUpdate ? R.string.lebian_update_available_force_update_hint : R.string.lebian_update_available_update_hint;
        String message = res.getString(resId);
        boolean haveInstallPermission= false;
        if (Build.VERSION.SDK_INT >= 26) {//Build.VERSION_CODES.O = 26
            Object canRequestPackageInstalls = callPromptActivityParcel("canRequestPackageInstalls", null, null);
            if( canRequestPackageInstalls != null) {
                haveInstallPermission = (Boolean) canRequestPackageInstalls;
            }
            Log.d(TAG, "haveInstallPermission: ="+haveInstallPermission);
            if (!haveInstallPermission) {
                if (getApplicationInfo().targetSdkVersion >= 26) {
                    resId = R.string.lebian_install_needs_uri_permission;
                    if (resId > 0) {
                        message += res.getString(resId);
                    }
                } else {
                    resId = R.string.lebian_install_failed_needs_uri_permission;
                    if (resId > 0) {
                        message += res.getString(resId);
                    }
                }
            }
        }
        builder.setMessage(message);
        builder.setTitle(res.getString(R.string.lebian_update_available));

        builder.setPositiveButton(res.getString(R.string.lebian_install_yes), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("overInsPackage", new Class[]{boolean.class, String.class}, new Object[]{forceUpdate, apkPath});
            }
        });

        if (!forceUpdate||BwbxUI.getGlobalBoolean(PromptActivity.this, "ENABLE_EXIT_BUTTON", false)) {
            resId = forceUpdate ? R.string.lebian_quit_game : R.string.lebian_exit_dialog_no;
            builder.setNegativeButton(res.getString(resId), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    if (forceUpdate) {
                        callPromptActivityParcel("quitGame", null, null);
                    } else {
                        callPromptActivityParcel("cancelCheck",null,null);
                        finish();
                    }
                }
            });
        }

        if (!isFinishing()) {
            installDialog = builder.create();
            installDialog.setCancelable(false);
            installDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                        return true;
                    } else {
                        return false;
                    }
                }
            });
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                installDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
            }
            installDialog.show();
        }

    }

    // --------------------------------end----------------------------

    private void showUpdateDialog(final Serializable detail, final boolean dataConnection, final boolean forceUpdate, final long size, final boolean ncKillSelf, final boolean stopOtherDl) {
        Log.d(TAG, "showUpdateDialog enter detail:" + detail + " dataConnection:" + dataConnection + " ncKillSelf:" + ncKillSelf + " stopOtherDl:" + stopOtherDl + ", size=" + size);
        //判断是否使用的是GooglePlay更新
        Object isUseGooglePlayUpdate = callPromptActivityParcel("isUseGooglePlayUpdate", new Class[]{Serializable.class}, new Object[]{detail});
        boolean useGooglePlayUpdate = isUseGooglePlayUpdate == null ? false : (Boolean) isUseGooglePlayUpdate;
        Resources res = getResources();
        CustomDialog.Builder builder = new CustomDialog.Builder(this);

        int resId = R.string.lebian_dl_update_without_wifi;
        int resId2 = R.string.lebian_dl_update_wifi;

        if(useGooglePlayUpdate) {
            builder.setMessage(R.string.lebian_dl_update_with_google_play);
        }else {
            builder.setMessage(String.format(res.getString(dataConnection ? resId : resId2), ((float) (size)) / (1024.0f * 1024.0f)));
        }
        builder.setTitle(res.getString(R.string.lebian_hint));
        if (!forceUpdate) {
            builder.setCheckBox(res.getString(R.string.lebian_next_no_prompt), false, new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    PreferencesHelper.putBoolean(PromptActivity.this, PreferencesHelper.MODULE_PROMPT, "gameUpdate", isChecked);
                }
            });
        }
        resId = R.string.lebian_button_ok;
        resId2 = R.string.lebian_dl_dl_background;
        builder.setPositiveButton(res.getString(forceUpdate ? resId : resId2), new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (forceUpdate) {
                    PreferencesHelper.putBoolean(PromptActivity.this, PreferencesHelper.MODULE_GAMEINFO, "selfKill", true);
                    Boolean ad = ((Boolean) callPromptActivityParcel("alreadyDownloaded", new Class[]{Serializable.class}, new Object[]{detail}));
                    boolean alreadyDownloaded = ad == null ? false : ad.booleanValue();
                    if (!alreadyDownloaded) {
                        callPromptActivityParcel("switchToUpdate", new Class[]{Serializable.class, boolean.class, boolean.class}, new Object[]{detail, ncKillSelf, stopOtherDl});
                    } else {
                        callPromptActivityParcel("restartGame", new Class[]{Serializable.class}, new Object[]{detail});
                    }
                } else {
                    Boolean ad = ((Boolean) callPromptActivityParcel("alreadyDownloaded", new Class[]{Serializable.class}, new Object[]{detail}));
                    boolean alreadyDownloaded = ad == null ? false : ad.booleanValue();
                    if (!alreadyDownloaded) {
                        callPromptActivityParcel("downloadComponent", new Class[]{Serializable.class}, new Object[]{detail});
                        callPromptActivityParcel("cancelCheck",null,null);
                        finish();
                    }else {
                        finish();
                    }
                }
                PreferencesHelper.putBoolean(PromptActivity.this, PreferencesHelper.MODULE_PROMPT, "gameUpdate", false);
            }
        });

        if (!forceUpdate) {
            builder.setNegativeButton(res.getString(R.string.lebian_no_update), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Boolean ad = ((Boolean) callPromptActivityParcel("alreadyDownloaded", new Class[]{Serializable.class}, new Object[]{detail}));
                    boolean alreadyDownloaded = ad == null ? false : ad.booleanValue();
                    if (BwbxUI.getGlobalBoolean(PromptActivity.this, "DOWNLOAD_AFTER_QUIT", true) && !alreadyDownloaded && !dataConnection && forceUpdate)
                        callPromptActivityParcel("downloadComponent", new Class[]{Serializable.class, Boolean.class}, new Object[]{detail, true});
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                    PreferencesHelper.putBoolean(PromptActivity.this, PreferencesHelper.MODULE_PROMPT, "refusedByUser", true);
                }
            });
        } else if (BwbxUI.getGlobalBoolean(PromptActivity.this, "ENABLE_EXIT_BUTTON", false)) {
            builder.setNegativeButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    Boolean ad = ((Boolean) callPromptActivityParcel("alreadyDownloaded", new Class[]{Serializable.class}, new Object[]{detail}));
                    boolean alreadyDownloaded = ad == null ? false : ad.booleanValue();
                    if (BwbxUI.getGlobalBoolean(PromptActivity.this, "DOWNLOAD_AFTER_QUIT", true) && !alreadyDownloaded && !dataConnection && forceUpdate)
                        callPromptActivityParcel("downloadComponent", new Class[]{Serializable.class, Boolean.class}, new Object[]{detail, true});
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                    callPromptActivityParcel("quitGame", null, null);
                }
            });
        }

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }

    private void showNotEnoughSpaceDialog(final boolean forceUpdate, final long size) {
        boolean hasSD = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setTitle(res.getString(R.string.lebian_not_enought_space));
        long requiredSize = size;
        if (!hasSD)
            requiredSize += (20 << 20);
        String body = String.format(res.getString(R.string.lebian_storage_space_requirement_dload), requiredSize / (float) (1024 * 1024), hasSD ? res.getString(R.string.lebian_storage_sd) : res.getString(R.string.lebian_storage_phone));
        builder.setMessage(body);

        builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                if (forceUpdate)
                    callPromptActivityParcel("quitGame", null, null);

            }
        });
        Dialog notEnoughSpaceDialog = builder.create();
        notEnoughSpaceDialog.setCancelable(false);
        notEnoughSpaceDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            notEnoughSpaceDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!notEnoughSpaceDialog.isShowing() && !isFinishing()) {
            notEnoughSpaceDialog.show();
        }
    }

    private void showDownloadAll(long size, final boolean zipExists, final boolean dataConnection,int behavior) {
        Log.d(TAG, "showDownloadAll ENTER");

        Resources res = getResources();
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        int resId = R.string.lebian_first_dialog_note;
        int resId1 = R.string.lebian_first_dialog_note_al;
        builder.setMessage(String.format(res.getString(dataConnection ? resId : resId1), ((float) (size)) / (1024.0f * 1024.0f)));
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setPositiveButton(res.getString(R.string.lebian_dl_dl_background), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                if (!zipExists)
                    sendBroadcast(new Intent(getPackageName() + ".action.DOWNLOAD_ALL"), null);
                else
                    BwbxUI.switchToDownloadFullRes(PromptActivity.this);
                click(BwbxUI.getInt(PromptActivity.this, "DIALOG_TYPE_FIRST", 0), 1);
            }
        });
        if (behavior != TestUnit.BEHAVIOR_B1_FIRST_DIALOG_BG_DOWNLOAD_ONE_BUTTON) {
            resId = behavior == TestUnit.BEHAVIOR_D1_FIRST_DIALOG_BG_DOWNLOAD_CANCEL_BUTTON?R.string.lebian_button_cancel:R.string.lebian_download_later;
            builder.setNegativeButton(res.getString(resId), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callPromptActivityParcel("cancelCheck", null, null);
                    finish();
                    sendBroadcast(new Intent(getPackageName() + ".action.DOWNLOAD_ALL_LATER"), null);
                    click(BwbxUI.getInt(PromptActivity.this, "DIALOG_TYPE_FIRST", 0), 2);
                }
            });
        }

        Dialog downloadAll = builder.create();
        downloadAll.setCancelable(false);
        downloadAll.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        if (!downloadAll.isShowing()) {
            downloadAll.show();
        }

    }

    private void showChooseBwbx(long size, final int zipType, final boolean lbresLater, final Bundle bundle) {
        Log.d(TAG, "showChooseBwbx ENTER");

        Resources res = getResources();
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        int resId = R.string.lebian_choose_by_user_bwbx;
        if (zipType == 2)
            resId = R.string.lebian_choose_by_user_twice_load;
        builder.setMessage(String.format(res.getString(resId), ((float) (size)) / (1024.0f * 1024.0f)));
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setPositiveButton(res.getString(R.string.lebian_download_now), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck", null, null);
                finish();
                click(BwbxUI.getInt(PromptActivity.this, "DIALOG_TYPE_OLD_USER_FIRST", 0), 1);
                if (lbresLater)
                    sendBroadcast(new Intent(getPackageName() + ".action.DOWNLOAD_FULL_RES_IN_MOBILE"), null);
                else
                    BwbxUI.switchToDownloadFullRes(PromptActivity.this, zipType, bundle);
            }
        });

        if (!BwbxUI.getGlobalBoolean(this, "CHOOSE_BY_USER_BWBX_FORCE", false)) {
            resId = lbresLater ? R.string.lebian_continue_game : R.string.lebian_quit_game;
            if (lbresLater) {
                builder.setNegativeButton(res.getString(resId), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        callPromptActivityParcel("cancelCheck", null, null);
                        finish();
                        click(BwbxUI.getInt(PromptActivity.this, "DIALOG_TYPE_OLD_USER_FIRST", 0), 2);
                    }
                });
            } else if (BwbxUI.getGlobalBoolean(PromptActivity.this, "ENABLE_EXIT_BUTTON", false)) {
                builder.setNegativeButton(res.getString(resId), new OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        callPromptActivityParcel("cancelCheck", null, null);
                        finish();
                        click(BwbxUI.getInt(PromptActivity.this, "DIALOG_TYPE_OLD_USER_FIRST", 0), 2);
                        callPromptActivityParcel("quitGame", null, null);
                    }
                });
            }
        }
        Dialog chooseBwbx = builder.create();
        chooseBwbx.setCancelable(false);
        chooseBwbx.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        if (!chooseBwbx.isShowing()) {
            chooseBwbx.show();
        }

    }

    private void showMergeErrDialog(int mergeErrType, String errContent, int mainChId) {//mergeErrType 1 is permissionError, 2 is provider error
        Log.d(TAG, "showMergeErrDialog enter");
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        int resId = -1;
        if (mergeErrType == 0) {
            if (errContent == null || errContent.trim().length() <= 0){
                return;
            }
            builder.setMessage(errContent);
        } else {
            if (mergeErrType == 1)
                resId = R.string.lebian_permiss_missing;
            else if (mergeErrType == 2) {
                resId = R.string.lebian_authorities_error_new;
            }
            else if (mergeErrType == 3)
                resId = R.string.lebian_lebian_flag_missing;
            else if (mergeErrType == 4)
                resId = R.string.lebian_main_chid_err;
            else if (mergeErrType == 5)
                resId = R.string.lebian_switch_err;
            else if (mergeErrType == 6)
                resId = R.string.lebian_jar_version_not_match_err;
            if(mergeErrType == 1||mergeErrType == 3)
                builder.setMessage(res.getString(resId) + errContent);
            else if(mergeErrType == 4)
                builder.setMessage(String.format(res.getString(resId), errContent,mainChId));
            else if(mergeErrType == 5)
                builder.setMessage(res.getString(resId));
            else if(mergeErrType == 2) {
                String errMessage=null;
                if(resId == 0) {
                    resId = R.string.lebian_authorities_error;
                    errMessage = res.getString(resId) + "Please change all \"%1$s:com.excelliance\" to \"%2$s:com.excelliance\" in AndroidManifest.xml, see the document we provided for details";
                } else {
                    errMessage = res.getString(resId);
                }
                builder.setMessage(String.format(errMessage,errContent,getPackageName()));
            } else if(mergeErrType == 6) {
                builder.setMessage( errContent + res.getString(resId) );
            }
        }

        resId =R.string.lebian_hint;
        builder.setTitle(res.getString(resId));

        resId = R.string.lebian_button_ok;
        builder.setPositiveButton(res.getString(resId), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                //callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog permissionDialog = builder.create();
        permissionDialog.setCancelable(false);
        permissionDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            permissionDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!permissionDialog.isShowing() && !isFinishing()) {
            permissionDialog.show();
        }
    }

    private void showRestartDialogForJJ() {
        Log.d(TAG, "showRestartDialogForJJ enter");
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        int resId = R.string.lebian_for_jj_restart;

        builder.setMessage(res.getString(resId));

        resId = R.string.lebian_hint;
        builder.setTitle(res.getString(resId));

        resId = R.string.lebian_button_ok;
        builder.setPositiveButton(res.getString(resId), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog restartDialog = builder.create();
        restartDialog.setCancelable(false);
        restartDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            restartDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!restartDialog.isShowing() && !isFinishing()) {
            restartDialog.show();
        }
    }

    private void showChooseResPatch(long size, boolean dataConnection, final int dlsZipType, final boolean forceDl, final Bundle patchInfo) {
        Log.d(TAG, "showChooseResPatch ENTER");

        Resources res = getResources();
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        int resId = dataConnection ? R.string.lebian_download_patch_res_without_wifi : R.string.lebian_download_patch_res;
        builder.setMessage(String.format(res.getString(resId), ((float) (size)) / (1024.0f * 1024.0f)));
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setPositiveButton(res.getString(R.string.lebian_download_now), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                BwbxUI.switchToDownloadFullRes(PromptActivity.this, dlsZipType, patchInfo);
            }
        });

        resId = forceDl ? R.string.lebian_quit_game : R.string.lebian_continue_game;
        if (!forceDl) {
            builder.setNegativeButton(res.getString(resId), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                    callPromptActivityParcel("bwbxContinue", null, null);
                }
            });
        } else if (BwbxUI.getGlobalBoolean(PromptActivity.this, "ENABLE_EXIT_BUTTON", false)) {
            builder.setNegativeButton(res.getString(resId), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                    callPromptActivityParcel("quitGame", null, null);
                }
            });
        }

        Dialog chooseBwbx = builder.create();
        chooseBwbx.setCancelable(false);
        chooseBwbx.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });

        if (!chooseBwbx.isShowing()) {
            chooseBwbx.show();
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        callPromptActivityParcel("onNewIntent", new Class[]{Intent.class}, new Object[]{intent});
    }

    private void showLoadingDialog() {
        Log.d(TAG, "showLoadingDialog enter");
        String packageName = getPackageName();
        Dialog loadDialog = new Dialog(this);
        Resources res = getResources();
        //获取背景图
        int backgroundImageId = getBackgroundImageId(this);
        if (backgroundImageId > 0) {
            Bitmap bitmap = BitmapFactory.decodeResource(res, backgroundImageId);
            if (bitmap != null) {
                LbUiWindowManager lbUiWindowManager = LbUiWindowManager.getInstance(this);
                int screenWidth = lbUiWindowManager.getScreenWidth(this);
                int screenHeight = lbUiWindowManager.getScreenHeight(this);
                //剪裁背景图
                bitmap = BitmapUtils.picture(this, bitmap, screenWidth, screenHeight);
                Drawable drawable = new BitmapDrawable(bitmap);
                getWindow().setBackgroundDrawable(drawable);
            }
        }
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.lebian_progress_dialog, null, false);
        TextView tips = view.findViewById(R.id.lebian_text_progress_loading);
        tips.setText(res.getString(R.string.lebian_loading_pls_wait));
        loadDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        loadDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        loadDialog.setContentView(view);
        loadDialog.setCancelable(false);
        loadDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            loadDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        loadDialog.show();
    }

    /**
     * 获取一张背景图片id
     *
     * @param context context
     * @return 背景图片id
     */
    private int getBackgroundImageId(Context context) {
        Resources mainRes = BwbxUI.getResources(context);
        Resources apkRes = BwbxUI.getApkResources(context);
        //获取名字为lebian_main_background_normal的背景图
        int backgroundId = apkRes.getIdentifier(SwitchView.BG_NAME, "drawable", context.getPackageName());
        if (backgroundId <= 0) {
            backgroundId = mainRes.getIdentifier(SwitchView.BG_NAME, "drawable", context.getPackageName());
        }
        //名字为lebian_main_background_normal的背景图不存在
        //寻找lebian_main_background_normal_x的背景图，x最大为9;
        if (backgroundId <= 0) {
            for (int i = 0; i < 10; i++) {
                backgroundId = apkRes.getIdentifier(SwitchView.BG_NAME + "_" + i, "drawable", context.getPackageName());
                //找到一张就退出循环
                if (backgroundId > 0) {
                    break;
                } else {
                    backgroundId = mainRes.getIdentifier(SwitchView.BG_NAME + "_" + i, "drawable", context.getPackageName());
                    //找到一张就退出循环
                    if (backgroundId > 0) {
                        break;
                    }
                }
            }
        }
        return backgroundId;
    }

    public void showSpaceNotEnough(long requiredSize){
        boolean hasSD = android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setTitle(res.getString(R.string.lebian_not_enought_space));

        if (!hasSD)
            requiredSize += (20 << 20);
        String body = String.format(res.getString(R.string.lebian_storage_space_requirement_dload), requiredSize / (float) (1024 * 1024), hasSD ? res.getString(R.string.lebian_storage_sd) : res.getString(R.string.lebian_storage_phone));
        builder.setMessage(body);

        builder.setPositiveButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }

    public void showNotNetworkDialog(){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setTitle(res.getString(R.string.lebian_network_error));
        builder.setMessage(res.getString(R.string.lebian_enable_internet_access));

        builder.setPositiveButton(res.getString(R.string.lebian_enable_now), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }

    public void showDloadFromWebsite(final String dealPath,boolean forceUpdate){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setMessage(res.getString(R.string.lebian_new_version_available));
        builder.setPositiveButton(res.getString(R.string.lebian_website_download), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                Intent dealIntent = new Intent(Intent.ACTION_VIEW);
                dealIntent.setData(Uri.parse(dealPath));
                startActivity(dealIntent);
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
            }
        });
        if (forceUpdate && BwbxUI.getGlobalBoolean(PromptActivity.this, "ENABLE_EXIT_BUTTON", false)) {
            builder.setNegativeButton(res.getString(R.string.lebian_quit_game), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                    callPromptActivityParcel("quitGame", null, null);
                }
            });
        }else{
            builder.setNegativeButton(res.getString(R.string.lebian_continue_game), new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    callPromptActivityParcel("cancelCheck",null,null);
                    finish();
                }
            });
        }

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }

    private void showSecIdErrDialog(String errMsg) {
        Log.d(TAG, "showSecIdErrDialog enter");
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        String msgBody = String.format(res.getString(R.string.lebian_secid_err), errMsg==null?"LEBIAN_SECID":errMsg);
        builder.setMessage(msgBody);

        builder.setTitle(res.getString(R.string.lebian_hint));

        builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                //callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog secIdErrDialog = builder.create();
        secIdErrDialog.setCancelable(false);
        secIdErrDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            secIdErrDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!secIdErrDialog.isShowing() && !isFinishing()) {
            secIdErrDialog.show();
        }
    }
    private void showTargetSdkVersionErrDialog() {
        Log.d(TAG, "showTargetSdkVersionErrDialog enter");
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setMessage(res.getString(R.string.lebian_target_sdk_version_err));
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                //callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog targetSdkVersionErrDialog = builder.create();
        targetSdkVersionErrDialog.setCancelable(false);
        targetSdkVersionErrDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            targetSdkVersionErrDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!targetSdkVersionErrDialog.isShowing() && !isFinishing()) {
            targetSdkVersionErrDialog.show();
        }
    }

    private void showInvalidPackageDialog(){
        CustomDialog.Builder builder = new CustomDialog.Builder(this);
        Resources res = getResources();
        builder.setTitle(res.getString(R.string.lebian_hint));
        builder.setMessage(res.getString(R.string.lebian_invalid_package));

        builder.setPositiveButton(res.getString(R.string.lebian_button_ok), new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                callPromptActivityParcel("cancelCheck",null,null);
                finish();
                callPromptActivityParcel("quitGame", null, null);
            }
        });

        Dialog updateDialog = builder.create();
        updateDialog.setCancelable(false);
        updateDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_SEARCH) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            updateDialog.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
        }
        if (!updateDialog.isShowing() && !isFinishing()) {
            updateDialog.show();
        }
    }

    private void showDownloadSuccessToast() {
        Log.d(TAG, "showDownloadSuccessToast enter");
        Resources res = getResources();
        String toastStr = res.getString(R.string.lebian_download_success);
        Toast.makeText(this, toastStr, Toast.LENGTH_SHORT).show();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish(); //延迟finish，不然toast会很快消失
            }
        }, 1000);
    }

    private Object callPromptActivityParcel(String name, Class[] type, Object[] args) {

        Parcelable promp=promptActivityParcel;
        try {
            Class clazz = BwbxUI.getClass("main.PromptActivityParcel");
            Method method = clazz.getDeclaredMethod(name, type);
            method.setAccessible(true);
            return method.invoke(promp, args);
        } catch (Exception e) {
            Log.d(TAG, "no PromptActivityParcel");
            e.printStackTrace();
        }

        return null;
    }

    private void click(final int dType, final int cType) {
        Intent intent = new Intent(getPackageName() + BwbxUI.getString(this, "ACTION_USER_CLICK", ""));
        intent.setPackage(getPackageName());
        intent.putExtra("dtype", dType);
        intent.putExtra("ctype", cType);
        sendBroadcast(intent, null);
    }
}