package com.gto.bt_sample_code;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.gainscha.gtspl_sdk.GTSPLActivity;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    Button mReadUhfBT,mSearchBT, mConnectBT, mDisconnectBT, mPrinterSetup, mPrintBarcode, mPrintFontCN,
            mPrintFontTW, mPrintBmp, mPrintBlock, mGetStatus, mGetSDKVersion,mWriteRfid,mWriteAndLockRfid,
            mSetGjbPwdBtn,mWriteGjbBtn,mReadGjbBtn,mPirntMonoBmpBtn,mQueryUhfBT,mCalibrationRfid,mPrintQRcode,mOthersettings,mSetupRfid,mWifiFrequency,
            mPrintBmpNew,mPrintBmpCompress;
    EditText mReadUhfET, mMacAddress, mPrinterStatusTxt, mSDKVersionTxt,mGJBDataET,mQueryUhfET;
    GTSPLActivity mGtsplCmdTest = new GTSPLActivity();

    //blue
    public BluetoothAdapter mBluetoothAdapter;
    public boolean mScanning;
    public Handler mHandler;
    public static final long SCAN_PERIOD = 3000;
    public static final int REQUEST_ENABLE_BT = 1;
    public BluetoothLeScanner mBluetoothLeScanner;
    public static String mMacAddr;
    int REQUEST_CODE_PERMISSION_LOCATION = 100;
    public Dialog mBTSearchDialog;
    private com.gto.bt_sample_code.BleAdatper mBTAdatper;
    private ListView mBTListView;
    private View mEmptyView;
    private int mCount=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mHandler = new Handler();

        mReadUhfET = findViewById(R.id.et_read_uhf);
        mReadUhfBT = findViewById(R.id.bt_read_uhf);
        mQueryUhfET = findViewById(R.id.et_query_uhf);
        mQueryUhfBT = findViewById(R.id.bt_query_uhf);
        mSearchBT = findViewById(R.id.search);
        mConnectBT = findViewById(R.id.connect);
        mDisconnectBT = findViewById(R.id.disconnect);
        mPrinterSetup = findViewById(R.id.setup);
        mPrintBarcode = findViewById(R.id.print_barcode);
        mPrintFontCN = findViewById(R.id.print_font_cn);
        mPrintFontTW = findViewById(R.id.print_font_tw);
        mPrintBmp = findViewById(R.id.print_bmp);
        mPirntMonoBmpBtn=findViewById(R.id.print_monochrome_bmp);
        mCalibrationRfid = findViewById(R.id.calibration_rfid);
        mPrintQRcode = findViewById(R.id.print_qrcode);
        mOthersettings =findViewById(R.id.othersettings);
        mWifiFrequency = findViewById(R.id.wifi_frequency);
        mSetupRfid =findViewById(R.id.setup_rfid);
        mPrintBmpNew = findViewById(R.id.print_bmp_new);
        mPrintBmpCompress = findViewById(R.id.print_bmp_compress);
        mPrintBlock = findViewById(R.id.print_block);
        mGetStatus = findViewById(R.id.get_printer_status);
        mGetSDKVersion = findViewById(R.id.get_sdk_version);
        mWriteRfid =findViewById(R.id.write_rfid);
        mWriteAndLockRfid =findViewById(R.id.write_and_lock_rfid);

        mSetGjbPwdBtn=findViewById(R.id.set_gjb_status_btn);
        mWriteGjbBtn=findViewById(R.id.write_gjb_btn);
        mReadGjbBtn=findViewById(R.id.read_gjb_btn);

        mReadUhfBT.setOnClickListener(this);
        mQueryUhfBT.setOnClickListener(this);
        mSearchBT.setOnClickListener(this);
        mConnectBT.setOnClickListener(this);
        mDisconnectBT.setOnClickListener(this);
        mPrinterSetup.setOnClickListener(this);
        mPrintBarcode.setOnClickListener(this);
        mPrintFontCN.setOnClickListener(this);
        mPrintFontTW.setOnClickListener(this);
        mPrintBmp.setOnClickListener(this);
        mPirntMonoBmpBtn.setOnClickListener(this);
        mCalibrationRfid.setOnClickListener(this);
        mPrintQRcode.setOnClickListener(this);
        mOthersettings.setOnClickListener(this);
        mWifiFrequency.setOnClickListener(this);
        mSetupRfid.setOnClickListener(this);
        mPrintBmpNew.setOnClickListener(this);
        mPrintBmpCompress.setOnClickListener(this);
        mPrintBlock.setOnClickListener(this);
        mGetStatus.setOnClickListener(this);
        mGetSDKVersion.setOnClickListener(this);
        mWriteRfid.setOnClickListener(this);
        mWriteAndLockRfid.setOnClickListener(this);
        mSetGjbPwdBtn.setOnClickListener(this);
        mWriteGjbBtn.setOnClickListener(this);
        mReadGjbBtn.setOnClickListener(this);

        mMacAddress = findViewById(R.id.macaddress);
        mPrinterStatusTxt = findViewById(R.id.printer_status_txt);
        mSDKVersionTxt = findViewById(R.id.sdk_version_txt);
        mGJBDataET=findViewById(R.id.ed_read_gjb);

        //set to print mode
        mGtsplCmdTest.GTSPL_setCmdSendMode("P");

        //save CIRCLE.BMP to loacal file
        getAssetsFile();
        checkPermissions();

        initialDialog();

    }

    private void initialDialog() {
        mBTSearchDialog = new Dialog(MainActivity.this);
        mBTSearchDialog.setContentView(R.layout.bt_devicelist_dialog);
        mBTSearchDialog.setCancelable(true);

        mBTListView = mBTSearchDialog.findViewById(R.id.bt_list);
        mEmptyView = mBTSearchDialog.findViewById(R.id.empty_view);

        mBTAdatper = new com.gto.bt_sample_code.BleAdatper(MainActivity.this);
        mBTListView.setEmptyView(mEmptyView);

        mBTListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String mac = ((TextView) mBTListView.getChildAt(i).findViewById(R.id.bt_item_mac)).getText().toString();
                mBTSearchDialog.cancel();
                //begin index包含，endindex不包含
                mMacAddr = mac.subSequence(0, 3) + "1" + mac.subSequence(4, 17); //把dc:0d的0d改為1d
                mMacAddress.setText(mMacAddr);
            }
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.search:
                if (chkIsSupportBLE()) {
                    if (!mBluetoothAdapter.isEnabled()) {
                        Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                        startActivityForResult(enableBtIntent,REQUEST_ENABLE_BT);
                    }
                    if (mBluetoothLeScanner != null) {
                        scanLeDevice(true);
                    }

                    mBTSearchDialog.show();
                    customDialogSize(mBTSearchDialog, MainActivity.this, 0.9f, 0.5f);
                    mBTListView.setAdapter(mBTAdatper);
                }

                break;
            case R.id.connect:
                if (mMacAddress.getText().toString().isEmpty()) {
                    Toast.makeText(this, "The macaddress column is empty", Toast.LENGTH_SHORT).show();
                } else {
                    boolean isConnect = mGtsplCmdTest.GTSPL_openPort(mMacAddress.getText().toString().trim().toUpperCase()); // 要大寫
                    if (isConnect) {
                        Toast.makeText(this, "Connect to BT succesfully.", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "Fail to connect to BT.", Toast.LENGTH_SHORT).show();
                    }
                }
                break;
            case R.id.disconnect:
                boolean isDisconnect = mGtsplCmdTest.GTSPL_closePort();
                if (isDisconnect) {
                    Toast.makeText(this, "Disconnect succesfully.", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "Fail to disconnect.", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.setup:
                mGtsplCmdTest.GTSPL_setup(62, 45, 2, 6, 0, 3, 0, this);
                mGtsplCmdTest.GTSPL_sendCommand(this, "DIRECTION 1\n\n");
                Toast.makeText(this, "Setting Complete!", Toast.LENGTH_SHORT).show();
                break;
            case R.id.print_barcode:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_barcode(30, 30, "128", 100, 1, 0, 2, 2, "barcode1234567", this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.print_font_cn:
                //print simplified chinese font 24*24
                String cnTest = "默认简体中文测试：海天米醋白米醋1瓶450ml";
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_printerFont(100, 10, "TSS24.BF2", 0, 1, 1, cnTest, this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.print_font_tw: //hide
                String twTest = "預設繁體中文測試：海天米醋白米醋1瓶450ml";
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_printerFont(100, 10, "TST24.BF2.BF2", 0, 1, 1, twTest, this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.print_bmp:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_downloadBMP("CIRCLE.BMP", this);
                mGtsplCmdTest.GTSPL_sendCommand(this, "PUTBMP 150,30,\"CIRCLE.BMP\"\r\n");
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.print_monochrome_bmp:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_download_Not1BitDepthBMP("penguin.jpg", MainActivity.this);
                mGtsplCmdTest.GTSPL_sendCommand(MainActivity.this, "PUTBMP 10,10,\"penguin.jpg\"\r\n");
                mGtsplCmdTest.GTSPL_printLabel(1, 1, MainActivity.this);
                break;
            case R.id.calibration_rfid:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_LabelCalibration(this);
                break;
            case R.id.print_qrcode:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_qrcode(300, 100, "H", 4, "A", 0, "ABCabc123", this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.othersettings:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_genericDefault(this);
                mGtsplCmdTest.GTSPL_sensorDefault(this);
                mGtsplCmdTest.GTSPL_rfidSetupDefault(this);
                mGtsplCmdTest.GTSPL_setDirectionAndMirror(1, 1, this);
                mGtsplCmdTest.GTSPL_setShift(00, this);
                mGtsplCmdTest.GTSPL_printReverse(160, 160, 160, 160, this);
                mGtsplCmdTest.GTSPL_setOffset(20, this);
                mGtsplCmdTest.GTSPL_setCutMode(0, 2, this);
                mGtsplCmdTest.GTSPL_setAfterPrintAction(3, this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.wifi_frequency:
                mGtsplCmdTest.GTSPL_WifiFrequency("5G",this);
                break;
            case R.id.setup_rfid:
                mGtsplCmdTest.GTSPL_Set_RFIDPorcedure(3,20,32,4,"N",3,3,"300",this);
                Toast.makeText(this, "Setting Complete!", Toast.LENGTH_SHORT).show();
                break;
            case R.id.print_block: //hide
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                String sBlock = "block 測試 -- 默认简体中文测试：海天米醋白米醋1瓶450ml --";
                mGtsplCmdTest.GTSPL_printFontBlock("15", "15", "790", "90",
                        "TSS24.BF2", "0", "1", "1",
                        "1", "1",sBlock,this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.write_rfid:
                mGtsplCmdTest.GTSPL_writeUHF("H", 2, 12, "E", "11223344556677889900AABB",this);
                mGtsplCmdTest.GTSPL_printLabel(1,1,this);
                Toast.makeText(this,"Wrote Data：Hex format,block no.= 2, write 12 bytes, EPC Bank, data=11223344556677889900AABB",Toast.LENGTH_LONG).show();
                break;
            case R.id.bt_read_uhf:
                mReadUhfET.setText("");
                final String ans_read = mGtsplCmdTest.GTSPL_readUHF(
                        "H",2,12,"E",MainActivity.this);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mReadUhfET.setTextColor(getResources().getColor(
                            R.color.colorAccent, null));
                }
                mReadUhfET.setText("GEN2 EPC: " + ans_read);
                break;
            case R.id.bt_query_uhf:
                mQueryUhfET.setText("");
                final String ans_query = mGtsplCmdTest.GTSPL_readUHFQ(
                        "H",1,0,MainActivity.this);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mQueryUhfET.setTextColor(getResources().getColor(
                            R.color.colorAccent, null));
                }
                mQueryUhfET.setText("GEN2 EPC: " + ans_query);
                break;
            case R.id.write_and_lock_rfid: //hide
                mGtsplCmdTest.GTSPL_writeUHF("H",2 , 12, "E", "11223344556677889900AABB",this);
                mGtsplCmdTest.GTSPL_AccessPWD_Action("S","12345678",this);
                mGtsplCmdTest.GTSPL_AccessPWD_Action("L","12345678",this);
                mGtsplCmdTest.GTSPL_EPCPWD_Action("L","12345678",this);
                mGtsplCmdTest.GTSPL_printLabel(1,1,this);
                Toast.makeText(this,"Wrote Data：as above cmd. Wrote Access PWD:12345678",Toast.LENGTH_LONG).show();
                break;
            case R.id.set_gjb_status_btn: //set GJB Status
                mGtsplCmdTest.GTSPL_Set_GJB_Pwd("S","S","11112222","22221111",this);
                mGtsplCmdTest.GTSPL_Set_GJB_Status("E","A","11112222",this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                Toast.makeText(this,"Set EPC Status:R & W",Toast.LENGTH_LONG).show();
                break;
            case R.id.write_gjb_btn: //write gjb epc data
                mGtsplCmdTest.GTSPL_writeGJB("H",2,12,"E","404041414242434344444545","12345678",this);
                mGtsplCmdTest.GTSPL_Set_GJB_Pwd("W","S","87654321","12345678",this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                Toast.makeText(this,"Wrote Data：404041414242434344444545",Toast.LENGTH_LONG).show();
                break;
            case R.id.read_gjb_btn: // read gjb epc data
                mGJBDataET.setText("");
                final String result = mGtsplCmdTest.GTSPL_readGJB(
                        "H",2,12,"E","33334444",MainActivity.this);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mGJBDataET.setTextColor(getResources().getColor(
                            R.color.colorAccent, null));
                }
                mGJBDataET.setText("GJB EPC : " + result);
                break;
            case R.id.get_printer_status:
                String status = mGtsplCmdTest.GTSPL_printersStatus(1000);
                setPrinterStatusToUI(status);
                break;
            case R.id.get_sdk_version:
                String version = mGtsplCmdTest.GTSPL_getSDKVersion(0, this);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    mSDKVersionTxt.setTextColor(getResources().getColor(R.color.colorAccent, null));
                }
                mSDKVersionTxt.setText("SDK Version:" + version);
                break;
            case R.id.print_bmp_new:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_printBMP(-500,30,400,300,1,"Duck.gif",this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
            case R.id.print_bmp_compress:
                mGtsplCmdTest.GTSPL_clearBuffer(this);
                mGtsplCmdTest.GTSPL_printBMP_Compression(-500,30,400,300,"Duck.gif",this);
                mGtsplCmdTest.GTSPL_printLabel(1, 1, this);
                break;
        }
    }


    //將assets中檔案存入手機
    private void getAssetsFile() {
        AssetManager assetManager = getAssets();
        InputStream inputStream;
        BufferedInputStream bis;
        ByteArrayOutputStream bos = null;
        try {
            inputStream = assetManager.open("CIRCLE.BMP");
            int dataLength = inputStream.available();
            bis = new BufferedInputStream(inputStream);
            byte[] buffer = new byte[dataLength];
            int len = 0;
            bos = new ByteArrayOutputStream();
            while ((len = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, len);
            }


            File dir = new File(String.valueOf(getExternalFilesDir("")));
            String pathName = dir.getAbsolutePath() + "/" + "CIRCLE" + ".BMP";
            File file = new File(pathName);
            if (!file.exists()) {
                FileOutputStream output = new FileOutputStream(file);
                output.write(bos.toByteArray());
                output.close();
            }
            bis.close();
            bos.close();
            inputStream.close();

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

    //印表機狀態
    private void setPrinterStatusToUI(String status) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mPrinterStatusTxt.setTextColor(getResources().getColor(R.color.colorAccent, null));
        }
        switch (status) {
            case "00":
                mPrinterStatusTxt.setText("Printer Status : Normal");
                break;
            case "01":
                mPrinterStatusTxt.setText("Printer Status : Head opened");
                break;
            case "02":
                mPrinterStatusTxt.setText("Printer Status : Paper Jam");
                break;
            case "03":
                mPrinterStatusTxt.setText("Printer Status : Paper Jam and head opened");
                break;
            case "04":
                mPrinterStatusTxt.setText("Printer Status : Out of paper");
                break;
            case "05":
                mPrinterStatusTxt.setText("Printer Status : Out of paper and head opened");
                break;
            case "08":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon");
                break;
            case "09":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon and head opened");
                break;
            case "0A":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon and paper jam");
                break;
            case "0B":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon, paper jam and head opened");
                break;
            case "0C":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon and out of paper");
                break;
            case "0D":
                mPrinterStatusTxt.setText("Printer Status : Out of ribbon, out of paper and head opened");
                break;
            case "10":
                mPrinterStatusTxt.setText("Printer Status : Pause");
                break;
            case "20":
                mPrinterStatusTxt.setText("Printer Status : Printing");
                break;
            case "80":
                mPrinterStatusTxt.setText("Printer Status : Other error");
                break;
        }


    }


    //============================================藍芽功能===============================================


    //檢查是否支援藍芽ble
    public boolean chkIsSupportBLE() {
        // Use this check to determine whether BLE is supported on the device.  Then you can
        // selectively disable BLE-related features.
        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            Toast.makeText(this, "Bluetooth isn't supported on the device", Toast.LENGTH_SHORT).show();
            return false;
        }

        // Initializes a Bluetooth adapter.  For API level 18 and above, get a reference to
        // BluetoothAdapter through BluetoothManager.
        final BluetoothManager bluetoothManager =
                (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = bluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth isn't supported on the device.", Toast.LENGTH_SHORT).show();
            return false;
        }
        mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
        return true;
    }

    //掃描裝置
    public void scanLeDevice(final boolean enable) {
        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mScanning = false;
                    mBluetoothLeScanner.stopScan(mLeScanCallback);
                }
            }, SCAN_PERIOD);

            mScanning = true;
            mBluetoothLeScanner.startScan(mLeScanCallback);
        } else {
            mScanning = false;
            mBluetoothLeScanner.stopScan(mLeScanCallback);
        }
    }

    // Device scan callback.
    public ScanCallback mLeScanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            mBTAdatper.addDevice(result.getDevice());
            mBTAdatper.notifyDataSetChanged();
        }

        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e("maggie", errorCode + "");
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // User chose not to enable Bluetooth.
        if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
            //UIUtiltiy.setSnackbars((View) viewContent.getParent(), getResources().getString(R.string.bluetooth_not_allowed), BaseActivity.this, R.drawable.ic_error);

        } else if (requestCode == REQUEST_ENABLE_BT) {
            //開啟服務後返回要再取得一次scanner
            mBluetoothLeScanner = mBluetoothAdapter.getBluetoothLeScanner();
            scanLeDevice(true);
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //========================================permission======================================================

    /**
     * 检查权限
     */
    private void checkPermissions() {
        String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION};
        List<String> permissionDeniedList = new ArrayList<>();
        for (String permission : permissions) {
            int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                //onPermissionGranted(permission);
            } else {
                permissionDeniedList.add(permission);
            }
        }
        if (!permissionDeniedList.isEmpty()) {
            String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
            ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
        }
    }


    //客製化dialog大小 API16以後的作法,平板先不調整dilog大小
    public static void customDialogSize(Dialog dialog, Activity activity, float widthScale, float heightScale) {

        DisplayMetrics displayMetrics = new DisplayMetrics();//取得螢幕寬高
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int displayWidth = displayMetrics.widthPixels; //width in pixels
        int displayHeight = displayMetrics.heightPixels; //height in pixels
        WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(); // Initialize a new window manager layout parameters

        // Copy the alert dialog window attributes to new layout parameter instance
        layoutParams.copyFrom(dialog.getWindow().getAttributes());
        int dialogWindowWidth;
        int dialogWindowHeight;

        dialogWindowWidth = (int) (displayWidth * widthScale);
        dialogWindowHeight = (int) (displayHeight * heightScale);

        // Set the width and height for the layout parameters
        // This will bet the width and height of alert dialog
        layoutParams.width = dialogWindowWidth;
        layoutParams.height = dialogWindowHeight;

        // Apply the newly created layout parameters to the alert dialog window
        dialog.getWindow().setAttributes(layoutParams);

    }


}
