/*
 * Copyright (c) sea-base develo
 */

package mars.mobile;

//원도메인 라이센스  제작 sea-base

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DownloadManager;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.pm.Signature;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.net.http.SslError;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Parcelable;
import android.os.Process;
import android.provider.MediaStore;
import android.provider.Settings;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;

//import com.google.android.gms.ads.interstitial.InterstitialAd;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.coordinatorlayout.widget.CoordinatorLayout;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.ShareActionProvider;
import androidx.appcompat.widget.Toolbar;

import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.DownloadListener;
import android.webkit.GeolocationPermissions;
import android.webkit.HttpAuthHandler;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.MimeTypeMap;
import android.webkit.PermissionRequest;
import android.webkit.SslErrorHandler;
import android.webkit.URLUtil;
import android.webkit.ValueCallback;
import android.webkit.WebBackForwardList;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
//import com.google.android.gms.ads.InterstitialAd;
import com.google.firebase.FirebaseApp;
//import com.google.firebase.iid.FirebaseInstanceId;
//import com.google.firebase.iid.InstanceIdResult;
import com.google.firebase.messaging.FirebaseMessaging;
import com.mocoplex.adlib.AdlibManager;

import org.apache.http.HttpResponse;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Stack;

import kr.co.kcp.util.PackageState;

import static com.google.android.gms.location.LocationServices.getFusedLocationProviderClient;
//import static com.kakao.util.helper.Utility.getPackageInfo;


public class MainActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemReselectedListener {


    public boolean is기존코드사용안함여부 = true;


    public static Stack<String> urlHistory = new Stack<>();

    private static final String TAG = "MainActivity";
    private static final int FILECHOOSER_LOLLIPOP_REQ_CODE = 3;
    public static String token;
    public static String weblink = null;
    private ValueCallback<Uri> mUploadMessage;
    private ValueCallback<Uri[]> filePathCallbackLollipop;
    protected String mCameraPhotoPath;
    private Uri mCapturedImageURI;

    //새로 정의
    public ValueCallback<Uri> filePathCallbackNormal;
    public final static int FILECHOOSER_NORMAL_REQ_CODE = 2001;
    private Uri cameraImageUri = null;

    private static int Intpopupcount;
    private static int currentVersion;
    private static String currentVersionName;
    private boolean isTwoClickBack = false;
    private CharSequence mTitle;
    public static String Str_MyPhoneNumber;
    public static WebView webView, webView_menu;

    static Activity activity;
    static Context context;
    public static String now_url;
    public static int dv_width, dv_height;
    private static ProgressBar mProgressHorizontal;
    static Intent get_intent;
    private static String get_sdk_version;
    static MyAsyncTask myAsyncTask, myAsyncTask2;
    // final SharedPreferences prefs = null;
    private static final String PROPERTY_APP_VERSION = "appVersion";
    public static SharedPreferences prefs;
    private ShareActionProvider mShareActionProvider;
    FloatingActionButton home, write, company, hugi;
    private String webview_url;
    static Toolbar toolbar;
    public static LinearLayout Lbottom;
    static ActionBar v7_actionbar;
    private static AppBarLayout appbarlayout;
    private static CoordinatorLayout coordinatorlayout;
    private boolean screen_home_postion = false;
    private Context mContext;
    public static String Android_id;
    public static boolean registration_ready = false;
    private static Context ChromemContext;
    Point p;
    private Runnable mRunnable;
    private Handler mHandler;
    private static boolean IsClear = false, push_agree = false;
    private AdlibManager _amanager;

    private int FILECHOOSER_RESULTCODE = 1;

    String link_url;
    String param5, param6;
    public static boolean IsAppOpened = false;
    //팝업해결 위한 웹뷰
    protected WebView newWebView;
    CustomRelativeLayout popWindow;
    protected Button popup_button;
    private boolean isPageOpen;
    private Animation translateLeftAnim;
    private Animation translateRightAnim;
    private FrameLayout mContainer;

    int MY_PERMISSION_REQUEST_STORAGE = 1;

    DownloadManager.Request request;
    protected String fileExtension;

    public static final int PROGRESS_STAT_NOT_START = 1;
    public int m_nStat = PROGRESS_STAT_NOT_START;
    public static final int PROGRESS_DONE = 3;
    public static final int PROGRESS_STAT_IN = 2;
    public static final String ACTIVITY_RESULT = "ActivityResult";
    private final String SCHEME = "paysample://card_pay";

    SharedPreferences.Editor editor;

    private boolean token_refreshed;
    private long install_date;
    private String p_messsage = null, imgUrl, subject;
    private URL url;
    private Bitmap imgBitmap;
    private ImageView img;
    /// private SwipeRefreshLayout mSwipeRefreshLayout;
    private boolean message_found = false;
    private String arg1;

    private boolean hasLocation = false;

    private double now_longi, now_lati;
    private BottomNavigationView bottomNavigationView;
    private String imageFileName;
    //private InterstitialAd interstitial;


    private String recevied_mime_type;
    private SensorManager sensorManager;
    private Sensor accelerormeterSensor;
    private int currentSteps;
    private Sensor stepCountSensor;
    private PermissionRequest myRequest;
    private int MY_PERMISSIONS_REQUEST_RECORD_AUDIO;
    private int MY_PERMISSIONS_REQUEST_CAMERA;
    private int MY_PERMISSIONS_REQUEST_VIDEO;

    private long lastTime;
    private float speed;
    private float lastX;
    private float lastY;
    private float lastZ;
    private float x, y, z;

    private static final int SHAKE_THRESHOLD = 800;
    private static final int DATA_X = SensorManager.DATA_X;
    private static final int DATA_Y = SensorManager.DATA_Y;
    private static final int DATA_Z = SensorManager.DATA_Z;
    public static int cnt = 0;
    private String now_back_url;
    private LocationCallback locationCallback;
    private LocationControl locationControlTask;
    private FusedLocationProviderClient mFusedLocationClient;
    private LocationRequest mLocationRequest;
    private long UPDATE_INTERVAL = 5 * 1000;  /* 10 secs */
    private long FASTEST_INTERVAL = 2000; /* 2 sec */
    private String history_url;

    private boolean doubleBackToExitPressedOnce = false;
    private Handler backButtonHandler = new Handler();

    private final Runnable backButtonRunnable = new Runnable() {
        @Override
        public void run() {
            doubleBackToExitPressedOnce = false;
        }
    };


    public static void set_scan_result(final String url) {
        final String value = url;

        Log.d("bb", "scan=" + url);

        if (webView != null) {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:set_value('" + value + "')");
                }
            });
        }

/*
        if( url.startsWith("http://") || url.startsWith("https://")){
            if(webView!=null) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                      //  webView.loadUrl("javascript:set_value('"+value+"')");
                        webView.loadUrl(value);
                        //webView.loadUrl("javascript:alert('url 호출은 지원하지 않습니다')");//막으려면 주석풀기
                    }
                });
            }


        }else {
            if(webView!=null) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl("javascript:set_value('"+value+"')");
                    }
                });
            }
        }
       */


    }


    // private BottomNavigationView bottomNavigationView;


    @SuppressLint({"MissingPermission", "SuspiciousIndentation"})
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 활동 퍼미션 체크
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED) {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, 0);
            }
        }


        //  Toast.makeText(this, getKeyHash(getApplicationContext()), Toast.LENGTH_LONG).show();
        //Log.d(TAG, "getKeyHash = " + getKeyHash(getApplicationContext()));
        bottomNavigationView = findViewById(R.id.bottom_navigation);
        bottomNavigationView.setVisibility(View.GONE);

        // bottomNavigationView.setLabelVisibilityMode(LabelVisibilityMode.LABEL_VISIBILITY_UNLABELED);
        // bottomNavigationView.setSelectedItemId(R.id.action_two);
        // bottomNavigationView.getMenu().findItem(R.id.action_one).setChecked(false);
        // bottomNavigationView.clearFocus();
        //  bottomNavigationView.setItemTextAppearanceActive(1);
        bottomNavigationView.setOnNavigationItemReselectedListener(this);
        bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                // handle desired action here
                // One possibility of action is to replace the contents above the nav bar
                // return true if you want the item to be displayed as the selected item
                return true;
            }
        });


//        SharedPreferences.Editor  editor = MainActivity.prefs.edit();
//        editor.putString("param_intent_url", null);
//        editor.commit();


//띠배너시 활성화
//      mAdView = findViewById(R.id.adView);
//       AdRequest adRequest = new AdRequest.Builder().build();
//        mAdView.loadAd(adRequest);
//
        //    call_admob();

        /// setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        // setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER_PORTRAIT);
        Intent intent = new Intent(getApplicationContext(), SettingActivity.class);
        //  Intent intent = new Intent(getApplicationContext(),Received_listviewActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //  startActivity(intent);

        prefs = getSharedPreferences("pref", Context.MODE_PRIVATE);
        editor = prefs.edit();
        cnt = prefs.getInt("manbogi_value", 0);//추가된 코드
        push_agree = prefs.getBoolean("law_agree", false);
        Str_MyPhoneNumber = prefs.getString("Str_MyPhoneNumber", "error");//추가된 코드
        Android_id = prefs.getString("Android_id", "");//추가된 코드
        Log.d(TAG, "android_id= " + Android_id);
        token = prefs.getString("token", null);//추가된 코드
        token_refreshed = prefs.getBoolean("token_refreshed", false);
        message_found = prefs.getBoolean("message_found", false);

        if (!TextUtils.isEmpty(prefs.getString("token", "")))
            token = prefs.getString("token", null);

        Log.d(TAG, "MainActivity TOKEN==" + token);
        install_date = prefs.getLong("install_date", 0);// 가져온값이 없을때 false 값이 기본
        Log.d("bb", "now_ad_push_value" + prefs.getBoolean("ad_push_value", false));
        updateIconBadgeCount(getApplicationContext(), 0);


        mFusedLocationClient = getFusedLocationProviderClient(this);
        // Create the location request to start receiving updates

        mLocationRequest = new LocationRequest();
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        //  mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        mLocationRequest.setInterval(UPDATE_INTERVAL);
        mLocationRequest.setFastestInterval(FASTEST_INTERVAL);


        //실시간 좌표전송 끄기  위치
        getFusedLocationProviderClient(this).requestLocationUpdates(mLocationRequest, locationCallback = new LocationCallback() {
                    @Override
                    public void onLocationResult(LocationResult locationResult) {
                        // do work here
                        // onLocationChanged(locationResult.getLastLocation());
                        super.onLocationResult(locationResult);


                        if (locationResult == null) {
                            Toast.makeText(MainActivity.this, "일시적으로 위치 정보를 가져올수 없습니다 잠시후 다시 접속해 주세요", Toast.LENGTH_SHORT).show();
                            return;
                        }

                        for (Location location : locationResult.getLocations()) {
                            // Update UI with location data
                            // ...
                         //     Toast.makeText(MainActivity.this, location.getLatitude()+"경도"+location.getLongitude()   + "갱신됨", Toast.LENGTH_SHORT).show();
                         ///   webView.loadUrl("javascript:set_value_location('" + location.getLatitude() + "','" + location.getLongitude() + "')");
                            // Log.d(TAG, "H1");
                        }
                    }
                },
                Looper.myLooper());


        if (install_date == 0) {
            //  MyCustomAlertDialog();//광고 푸시 수신 여부 동의 창 활성화
            editor.putLong("install_date", System.currentTimeMillis());
            // edit.commit();
            editor.putBoolean("nomal_push_value", true);
            editor.putBoolean("ad_push_value", true);
            editor.commit();
        }

/*
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // Create channel to show notifications.
            String channelId = getString(R.string.default_notification_channel_id);
            String channelName = getString(R.string.default_notification_channel_name);
            NotificationManager notificationManager =
                    getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(new NotificationChannel(channelId,
                    channelName, NotificationManager.IMPORTANCE_HIGH));
        }*/


        //    param_intent_url =  prefs.getString("param_intent_url", null);

        if (message_found) {
            Log.d("bb", "message_founded");
            p_messsage = prefs.getString("p_messsage", null);
            subject = prefs.getString("subject", null);
            weblink = prefs.getString("weblink", null);
            imgUrl = prefs.getString("imgUrl", null);
            arg1 = prefs.getString("arg1", null);

            if (!TextUtils.isEmpty(p_messsage))
                onNewIntent(getIntent());

            MyPushCustomAlertDialog();
        }

        Button subscribeButton = findViewById(R.id.subscribeButton);
        subscribeButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // [START subscribe_topics]
                FirebaseMessaging.getInstance().subscribeToTopic("news_test");
                // [END subscribe_topics]

                // Log and toast
                String msg = getString(R.string.msg_subscribed);
                Log.d(TAG, msg);
                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });

        ///////////////////////
        // Get token
        FirebaseApp.initializeApp(getApplicationContext());

        FirebaseMessaging.getInstance().subscribeToTopic("news_test");


        //        //String token = FirebaseInstanceId.getInstance().getToken();

/*
        FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
            if(task.isComplete()){
                String token = task.getResult();
                editor.putString("token", token);
                editor.commit();
                regist task1 = new regist();
                task1.execute(getResources().getString(R.string.Server_regid_url), token, Str_MyPhoneNumber, "");

            }
        });

        try {
            FirebaseMessaging.getInstance().getToken().addOnCompleteListener(task -> {
                if (task.isSuccessful()) {
                    final String token = task.getResult();
                    //GOT the token!
                }
            });
        } catch (Exception e) {
            // OMG, Firebase is used to log Firebase crash :)
            // I'm not sure if this will work...
          //  FirebaseCrashlytics.getInstance().recordException(e);
           // gotFBCrash = true;
        }
*/

//        FirebaseInstanceId.getInstance().getInstanceId()
//                .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
//                    @Override
//                    public void onComplete(@NonNull Task<InstanceIdResult> task) {
//                        if (!task.isSuccessful()) {
//                            Log.w(TAG, "getInstanceId failed", task.getException());
//                            return;
//                        }
//
//                        // Get new Instance ID token
//                        token = task.getResult().getToken();
//
//                        editor.putString("token", token);
//                        editor.commit();
//                        regist task1 = new regist();
//                        task1.execute(getResources().getString(R.string.Server_regid_url), token, Str_MyPhoneNumber, "");
//                    }
//                });

        // Log and toast
//        String msg = getString(R.string.msg_token_fmt, token);
//        Log.d(TAG, msg);
//        Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
        ////////////////////////

        Button logTokenButton = findViewById(R.id.logTokenButton);
        logTokenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Get token
                FirebaseApp.initializeApp(getApplicationContext());
                //String token = FirebaseInstanceId.getInstance().getToken();


//                FirebaseInstanceId.getInstance().getInstanceId()
//                        .addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
//                            @Override
//                            public void onComplete(@NonNull Task<InstanceIdResult> task) {
//                                if (!task.isSuccessful()) {
//                                    Log.w(TAG, "getInstanceId failed", task.getException());
//                                    return;
//                                }
//
//                                // Get new Instance ID token
//                                token = task.getResult().getToken();
//
//                            }
//                        });

                // Log and toast
                String msg = getString(R.string.msg_token_fmt, token);
                Log.d(TAG, msg);
                ///   Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });


        Intent get_sms_intent = new Intent(this.getIntent());
        param5 = get_sms_intent.getStringExtra("param5");
        param6 = get_sms_intent.getStringExtra("param6");


        IsAppOpened = true;

        //푸시가 온경우 해당 주소로 로딩한다.
        Intent get_intent = new Intent(this.getIntent());
        String param1 = get_intent.getStringExtra("order_id");
        String param2 = get_intent.getStringExtra("url");
        String param3 = get_intent.getStringExtra("arg1");
        String param4 = get_intent.getStringExtra("arg2");
        String param5 = get_intent.getStringExtra("arg3");

        //    setContentView(R.layout.activity_main);
        //toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);
        v7_actionbar = getSupportActionBar();
        ChromemContext = getApplicationContext();
        //_amanager.setAdsContainer(R.id.ads);


        //팝업 위해 추가된 레이아웃
        mContainer = (FrameLayout) this.findViewById(R.id.frameLayout1);
        //레이아웃 애니메이션
        translateLeftAnim = AnimationUtils.loadAnimation(this, R.anim.appear_from_right);
        translateRightAnim = AnimationUtils.loadAnimation(this, R.anim.disappear_to_right);
        SlidingPageAnimatinListener animListener = new SlidingPageAnimatinListener();
        translateLeftAnim.setAnimationListener(animListener);
        translateRightAnim.setAnimationListener(animListener);
        isPageOpen = false;
        ///mSwipeRefreshLayout =  findViewById(R.id.swipe_layout);

//        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
//            @Override
//            public void onRefresh() {
//                // do nothing
//                webView.reload();
//            }
//        });


        activity = this;
        context = getBaseContext();
        get_intent = getIntent();
        get_sdk_version = String.valueOf(Build.VERSION.SDK_INT);

        //디바이스 크기 가져오기
        DisplayMetrics dm = getApplicationContext().getResources().getDisplayMetrics();
        dv_width = dm.widthPixels;
        dv_height = dm.heightPixels;
        Log.d(TAG, dv_width + "<=width" + dv_height + "<=height");
        //여기까지


        getSupportActionBar().hide();
//        home.setVisibility(View.GONE);
        webView = (WebView) findViewById(R.id.webView);


        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            //noinspection deprecation
            CookieSyncManager.createInstance(this);
        }

        // use cookies to remember a logged in status
        CookieSyncManager.createInstance(this);
        //CookieManager.getInstance().removeAllCookie();
        CookieSyncManager.getInstance().startSync();

        CookieManager cookieManager = CookieManager.getInstance();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
            cookieManager.setAcceptThirdPartyCookies(webView, true);
            cookieManager.setAcceptCookie(true);
        } else {
            cookieManager.setAcceptCookie(true);
        }


        mProgressHorizontal = (ProgressBar) findViewById(R.id.mProgressHorizontal);

    /*    Str_MyPhoneNumber = telManager.getLine1Number();
        Str_MyPhoneNumber = Str_MyPhoneNumber.replace("+82", "0");*/
        //    Log.d(TAG, Str_MyPhoneNumber);


        WebSettings set = webView.getSettings();

        webView.getSettings().setGeolocationEnabled(true);//gps
        webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
        String userAgent = webView.getSettings().getUserAgentString();
        // webView.getSettings().setUserAgentString(userAgent + " hybrid_app1954");
        webView.getSettings().setUserAgentString(userAgent + " hybrid_android");
      //  webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setDatabaseEnabled(true);
        webView.getSettings().setDomStorageEnabled(true);
        webView.getSettings().setMediaPlaybackRequiresUserGesture(false);
       // webView.getSettings().setAppCacheEnabled(true);
        webView.getSettings().setTextZoom(100);
        webView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);

        // set.setAppCacheEnabled(false);
        set.setCacheMode(WebSettings.LOAD_NO_CACHE);

        set.setJavaScriptEnabled(true);
        set.setJavaScriptCanOpenWindowsAutomatically(true);
        //입력시 밑에 레이아웃이 키보드 위로 업되는 현상 막기위해 설정하는...
        set.setUseWideViewPort(true);
        set.setSupportZoom(true);
        set.setBuiltInZoomControls(true);
        set.setDisplayZoomControls(false); // 줌 버튼은 비활성화
        set.setLoadWithOverviewMode(true);


        // 웹뷰 설정시 필수.
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
            set.setAllowFileAccessFromFileURLs(true);
        set.setAllowFileAccess(true);


        webView.getSettings().setSupportMultipleWindows(true);// webcronclient 의 oncreatewindow 연동
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.addJavascriptInterface(new WebAppInterface(this), "Android");

        // = getIntent().getIntExtra("order_id",null);
        String get_order_id = get_intent.getStringExtra("order_id");
        String get_notice_order_id = get_intent.getStringExtra("notice_order_id");
        Log.d(TAG, get_sdk_version.toString());


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (0 != (getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE)) {
                WebView.setWebContentsDebuggingEnabled(true);
            }
        }

        webView.setBackgroundColor(0x00000000);//배경 검색 만들기 위해 웹뷰 배경을 투명하게 처리함
        myAsyncTask = new MyAsyncTask(getApplicationContext());

        webview_url = getResources().getString(R.string.home_url);


        if (param2 == null || TextUtils.isEmpty(param2)) {
            Log.d(TAG, "AAA");
            myAsyncTask.execute(webview_url, "webView", "");
        } else {
            Log.d(TAG, "bbb");
            myAsyncTask.execute(param2, "webView", "");
        }

        check_app_version();

        mRunnable = new Runnable() {
            @Override
            public void run() {
                p = new Point();
                p.x = 0;
                p.y = 450;
                // if(Intpopupcount<17)
                //     showPopup(MainActivity.this, p);
                Log.d(TAG, Intpopupcount + "다");
            }
        };

        mHandler = new Handler();
        mHandler.postDelayed(mRunnable, 3000);//3초후 팝업 뛰운다
        mContext = getApplicationContext();
        registration_ready = prefs.getBoolean("registration_ready", false);// 전에 gcm 이 정상적으로 등록되었었는지 확인


        if (prefs.getBoolean("is_my_msg", false))    // 도착한 메시지가 있을경우 0으로 리셋
        {
            editor.putBoolean("is_my_msg", false);//추가코드
            editor.putInt("msg_count", 0);
            editor.commit();
            updateIconBadgeCount(getApplicationContext(), 0);

        }

        webView.setWebChromeClient(new ChromeClient(this) {
            @Override
            public void doUpdateVisitedHistory (WebView view,
                                                String url,
                                                boolean isReload){
                Log.d("bb",url + "<<doUpdateVisitedHistory");

             //   history_url= now_url;
              now_url = url;
            }
            @Override
            public void onPermissionRequest(final PermissionRequest request) {
                myRequest = request;

                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                    for (String permission : request.getResources()) {
                        switch (permission) {
                            case "android.webkit.resource.AUDIO_CAPTURE": {
                                askForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
                                break;
                            }
                            case Manifest.permission.RECORD_AUDIO: {
                                askForPermission(request.getOrigin().toString(), Manifest.permission.RECORD_AUDIO, MY_PERMISSIONS_REQUEST_RECORD_AUDIO);
                                break;
                            }
                            case Manifest.permission.CAMERA: {
                                askForPermission(request.getOrigin().toString(), Manifest.permission.CAMERA, MY_PERMISSIONS_REQUEST_CAMERA);
                                break;
                            }
                            case "android.webkit.resource.VIDEO_CAPTURE": {
                                askForPermission(request.getOrigin().toString(), Manifest.permission.CAMERA, MY_PERMISSIONS_REQUEST_VIDEO);
                                break;
                            }

                        }
                    }
                }
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public void askForPermission(String origin, String permission, int requestCode) {
                Log.d("WebView", "inside askForPermission for" + origin + "with" + permission);

                if (ContextCompat.checkSelfPermission(getApplicationContext(),
                        permission)
                        != PackageManager.PERMISSION_GRANTED) {

                    // Should we show an explanation?
                    if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
                            permission)) {

                        // Show an expanation to the user *asynchronously* -- don't block
                        // this thread waiting for the user's response! After the user
                        // sees the explanation, try again to request the permission.

                    } else {

                        // No explanation needed, we can request the permission.

                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{permission},
                                requestCode);
                    }
                } else {
                    myRequest.grant(myRequest.getResources());
                }
            }

            @Override
            public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
                Log.d(TAG, "onGeolocationPermissionsShowPrompt PASSED");

                final String myOrigin = origin;
                final GeolocationPermissions.Callback myCallback = callback;

                prefs = getSharedPreferences("pref", getApplicationContext().MODE_PRIVATE);
                SharedPreferences.Editor edit = prefs.edit();
                Log.d(TAG, "X1==");
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setTitle("알림 메세지");

                builder.setMessage(getResources().getString(R.string.app_name) + "의 위치 확인 요청에 승인 하시겠습니까?");

                builder.setPositiveButton("수락", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int id) {
                        //   myCallback.invoke(myOrigin, true, false);
                        myCallback.invoke(myOrigin, true, false);
                        SharedPreferences.Editor edit = prefs.edit();
                        edit.putBoolean("keyagree", true);
                        edit.commit();

                    }
                });
                builder.setNegativeButton("거부", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        myCallback.invoke(myOrigin, false, false);
                        SharedPreferences.Editor edit = prefs.edit();
                        edit.putBoolean("keyagree", false);
                        edit.commit();
                    }
                });

                //  Log.d(TAG,"X1=");
                AlertDialog alert = builder.create();
                //    Log.d(TAG,"keyagree"+String.valueOf(prefs.getBoolean("keyagree"));
                if (!prefs.getBoolean("keyagree", false))
                    alert.show();
                else myCallback.invoke(myOrigin, true, false);
              /* alert.show();
                myCallback.invoke(myOrigin, true, true);*/
                //  Log.d(TAG,"X1=");
            }

            public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
                openFileChooser(uploadFile);
            }

            // 	For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                mUploadMessage = uploadMsg;
                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                // i.setType("*/*");
                i.setType("image/*");
                startActivityForResult(Intent.createChooser(i, "파일 선택"), FILECHOOSER_RESULTCODE);
            }

            // For Android 4.1+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                // Log.d("MainActivity", "4.1+");
                openFileChooser(uploadMsg, acceptType);
            }

            // For Android 5.0+

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            public boolean onShowFileChooser(
                    WebView webView, ValueCallback<Uri[]> filePathCallback,
                    FileChooserParams fileChooserParams) {
                Log.d("MainActivity", "5.0+");

                // Callback 초기화 (중요!)
                if (filePathCallbackLollipop != null) {
                    filePathCallbackLollipop.onReceiveValue(null);
                    filePathCallbackLollipop = null;
                }
                filePathCallbackLollipop = filePathCallback;

                boolean isCapture = fileChooserParams.isCaptureEnabled();
                Log.d(TAG, "isCapture=" + isCapture);
                recevied_mime_type = Arrays.asList(fileChooserParams.getAcceptTypes()).toString();
                runCamera(isCapture);

                return true;
            }

//            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//            public boolean onShowFileChooser(
//                    WebView webView, ValueCallback<Uri[]> filePathCallback,
//                    FileChooserParams fileChooserParams) {
//                Log.d("MainActivity", "5.0+");
//
//                // Callback 초기화 (중요!)
//                if (filePathCallbackLollipop != null) {
//                    filePathCallbackLollipop.onReceiveValue(null);
//                    filePathCallbackLollipop = null;
//                }
//                filePathCallbackLollipop = filePathCallback;
//
//                boolean isCapture = fileChooserParams.isCaptureEnabled();
//                Log.d(TAG,"isCapture="+isCapture);
//                runCamera(isCapture);
//
//                return true;
//            }


            public void onProgressChanged(WebView view, int progress) {
                //  mProgressHorizontal.setProgress(progress);
                Log.d(TAG, progress + ".");

            }

            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                try {
                    popWindow = new CustomRelativeLayout(MainActivity.this);
                    mContainer.addView(popWindow);
                    newWebView = popWindow.getTheWebView();
                    popup_button = popWindow.getTheButton();
                    final ProgressBar popProgress = popWindow.getTheProgrss();
                    isPageOpen = true;
                    popWindow.startAnimation(translateLeftAnim);

                    WebSettings set1 = newWebView.getSettings();
                    set1.setJavaScriptEnabled(true);
                    set1.setSaveFormData(true);
                    set1.setJavaScriptCanOpenWindowsAutomatically(true);
                    set1.setUseWideViewPort(true);
                    set1.setDomStorageEnabled(true);
                    set1.setAllowFileAccess(true);
                    set1.setBuiltInZoomControls(true);
                    set1.setCacheMode(WebSettings.LOAD_NO_CACHE);
                    set1.setUserAgentString(userAgent + " hybrid_android");
                    newWebView.addJavascriptInterface(new WebAppInterface2(mContext), "Android_popup");

                    CookieManager cookieManager = CookieManager.getInstance();
                    cookieManager.setAcceptCookie(true);
                    newWebView.getSettings().setTextZoom(100);

                    if (Build.VERSION.SDK_INT >= 21) {
                        set1.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
                        cookieManager.setAcceptThirdPartyCookies(newWebView, true);
                    }

                    newWebView.setWebChromeClient(new WebChromeClient() {
                        @Override
                        public void onCloseWindow(WebView window) {
                            super.onCloseWindow(window);
                            if (newWebView != null) {
                                isPageOpen = false;
                                popWindow.startAnimation(translateRightAnim);
                                newWebView.setVisibility(View.GONE);
                            }
                        }

                        @Override
                        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
                            try {
                                new AlertDialog.Builder(view.getContext())
                                        .setTitle("알림")
                                        .setMessage(message)
                                        .setPositiveButton(android.R.string.ok, (dialog, which) -> result.confirm())
                                        .setCancelable(false)
                                        .create()
                                        .show();
                            } catch (Exception e) {
                                e.printStackTrace();
                                restartApp();
                            }
                            return true;
                        }
                    });

                    newWebView.setWebViewClient(new WebViewClient() {
                        @Override
                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                            try {
                                if (url.startsWith("intent:")) {
                                    return url_scheme_intent(view, url);
                                } else {
                                    newWebView.loadUrl(url);
                                    return true;
                                }
                            } catch (Exception e) {
                                e.printStackTrace(); // 로그에 예외 출력
                            }
                            return true;
                        }

                        @Override
                        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                            builder.setTitle(getResources().getString(R.string.app_name))
                                    .setMessage("SSL 인증서를 통해 보안접속을 하시겠습니까?")
                                    .setPositiveButton("예", (dialog, which) -> handler.proceed())
                                    .setNegativeButton("아니오", (dialog, which) -> handler.cancel())
                                    .setCancelable(false)
                                    .create()
                                    .show();
                        }
                    });

                    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
                    transport.setWebView(newWebView);
                    resultMsg.sendToTarget();

                } catch (Exception e) {
                    e.printStackTrace(); // 에러 발생 시 스택 트레이스 출력
                }
                return true;
            }



//            @Override
//            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
//
//
//
//                try {
//                    popWindow = new CustomRelativeLayout(MainActivity.this);
//                    mContainer.addView(popWindow);
//                    newWebView = popWindow.getTheWebView();
//                    popup_button = popWindow.getTheButton();
//                    final ProgressBar popProgress = popWindow.getTheProgrss();
//                    isPageOpen = true;
//                    popWindow.startAnimation(translateLeftAnim);
//
//                    WebSettings set1 = newWebView.getSettings();
//                    set1.setJavaScriptEnabled(true);
//                    set1.setSaveFormData(true);
//                    set1.setSavePassword(true);
//                    set1.setJavaScriptCanOpenWindowsAutomatically(true);
//                    set1.setUseWideViewPort(true);
//                    set1.setDomStorageEnabled(true);
//                    set1.setAllowFileAccess(true);
//                    set1.setBuiltInZoomControls(true);
//                    //   set1.setAppCacheEnabled(true);
//                    set1.setCacheMode(WebSettings.LOAD_NO_CACHE);
//                    set1.setUserAgentString(userAgent + " hybrid_android");
//                    newWebView.addJavascriptInterface(new WebAppInterface2(mContext), "Android_popup");
//                    //newWebView.setInitialScale(1);
//                    CookieManager cookieManager = CookieManager.getInstance();
//                    cookieManager.setAcceptCookie(true);
//                    newWebView.getSettings().setTextZoom(100);
//                    newWebView.getSettings().setTextSize(WebSettings.TextSize.NORMAL);
//
//                    if (Build.VERSION.SDK_INT >= 21) {
//                        set1.setMixedContentMode(0);
//                        cookieManager.setAcceptCookie(true);
//                        cookieManager.setAcceptThirdPartyCookies(newWebView, true);
//                    }
//
//                    newWebView.getSettings().setDisplayZoomControls(false);
//
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//                        newWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
//                        cookieManager.setAcceptThirdPartyCookies(newWebView, true);
//                        cookieManager.setAcceptCookie(true);
//                    } else {
//                        cookieManager.setAcceptCookie(true);
//                    }
//
//
//                    popup_button.setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View v) {
//
//                            mContainer.removeView(popWindow);
//                            newWebView.destroy();
//                            newWebView = null;
//                            Log.d(TAG, webView.isActivated() + "parent webview is activated");
//
//                            webView.setVisibility(View.VISIBLE);
//                            popup_button.setVisibility(View.GONE);
//
//
//                        }
//                    });
//
//
//                    newWebView.setOnTouchListener(new View.OnTouchListener() {
//                        @Override
//                        public boolean onTouch(View v, MotionEvent event) {        // TODO Auto-generated method stub
//
//
//                            switch (event.getAction()) {
//                                case MotionEvent.ACTION_DOWN:
//                                    ///	Toast.makeText(v.getContext(),"newWebView is touched", 3000).show();
//                                    ///	webView.setClickable(true);//안먹음
//                            }
//                            return false;
//                        }
//                    });
//
//
//                    newWebView.setDownloadListener(new DownloadListener() {
//
//
//                        @SuppressLint("DefaultLocale")
//
//                        @Override
//
//
//                        public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
//
//
//                            request = new DownloadManager.Request(Uri.parse(url));
//
//                            MimeTypeMap mimetype_now = MimeTypeMap.getSingleton();
//
//
//                            String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
//                            //downloadFileAsync(url, fileName);
//                            Log.d(TAG, fileName);
//                            String mimeType = mimetype_now.getMimeTypeFromExtension(fileName);
//                            fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();
//
//
//                            // request.setMimeType(mimetype);
//                            request.setMimeType("application/" + fileExtension);
//                            //------------------------COOKIE!!------------------------
//                            String cookies = CookieManager.getInstance().getCookie(url);
//                            request.addRequestHeader("cookie", cookies);
//                            //------------------------COOKIE!!------------------------
//                            request.addRequestHeader("User-Agent", userAgent);
//                            request.setDescription(getResources().getString(R.string.app_name));
//                            request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
//                            request.allowScanningByMediaScanner();
//                            request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
//                            request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
//                            DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
//                            try {
//                                dm.enqueue(request);
//                            } catch (Exception e) {
//                                //  if(Build.VERSION.SDK_INT >= 23)
//                                //  checkPermission();
//                            }
//
//
//                        }
//
//                    });
//
//
//                    newWebView.setWebChromeClient(new WebChromeClient() {
//
//
//                        @Override
//                        public void onCloseWindow(WebView window) {
//                            super.onCloseWindow(window);
//                            //Toast.makeText(getApplicationContext(),"call close window", 3000).show();
//                            if (newWebView != null) {
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                newWebView.setVisibility(View.GONE);
//                            }
//                        }
//
//
//                        @Override
//                        public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
//
//                            // TODO Auto-generated method stub
//                            //return super.onJsAlert(view, url, message, result);
//
//                            if (newWebView != null) {
//                                try {
//                                    new AlertDialog.Builder(view.getContext())
//                                            .setTitle("알림")
//                                            .setIcon(R.mipmap.ic_launcher)
//                                            .setMessage(message)
//                                            .setPositiveButton(android.R.string.ok,
//                                                    new AlertDialog.OnClickListener() {
//                                                        public void onClick(DialogInterface dialog, int which) {
//                                                            result.confirm();
//                                                        }
//                                                    })
//                                            .setCancelable(false)
//                                            .create()
//                                            .show();
//                                } catch (Exception e) {
//                                    restartApp();
//                                    moveTaskToBack(true);
//                                    finish();
//                                    Process.killProcess(Process.myPid());
//
//                                }
//
//                            }
//                            return true;
//                        }
//
//
//                        @Override
//                        public boolean onJsConfirm(WebView view, String url, String message,
//                                                   final JsResult result) {
//                            // TODO Auto-generated method stub
//                            //return super.onJsConfirm(view, url, message, result);
//                            new AlertDialog.Builder(view.getContext())
//                                    .setTitle("알림")
//                                    .setMessage(message)
//                                    .setPositiveButton("네",
//                                            new AlertDialog.OnClickListener() {
//                                                public void onClick(DialogInterface dialog, int which) {
//                                                    result.confirm();
//                                                }
//                                            })
//                                    .setNegativeButton("아니오",
//                                            new AlertDialog.OnClickListener() {
//                                                public void onClick(DialogInterface dialog, int which) {
//                                                    result.cancel();
//                                                }
//                                            })
//                                    .setCancelable(false)
//                                    .create()
//                                    .show();
//                            return true;
//                        }
//
//
//                        public void openFileChooser(ValueCallback<Uri> uploadFile, String acceptType) {
//                            openFileChooser(uploadFile);
//                        }
//
//                        // 	For Android 3.0+
//                        public void openFileChooser(ValueCallback<Uri> uploadMsg) {
//                            mUploadMessage = uploadMsg;
//                            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
//                            i.addCategory(Intent.CATEGORY_OPENABLE);
//                            // i.setType("*/*");
//                            i.setType("image/*");
//                            startActivityForResult(Intent.createChooser(i, "파일 선택"), FILECHOOSER_RESULTCODE);
//                        }
//
//                        // For Android 4.1+
//                        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
//                            // Log.d("MainActivity", "4.1+");
//                            openFileChooser(uploadMsg, acceptType);
//                        }
//
//
//                        // For Android 5.0+
//                        @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
//                        public boolean onShowFileChooser(
//                                WebView webView, ValueCallback<Uri[]> filePathCallback,
//                                FileChooserParams fileChooserParams) {
//                            Log.d("MainActivity", "5.0+");
//
//                            // Callback 초기화 (중요!)
//                            if (filePathCallbackLollipop != null) {
//                                filePathCallbackLollipop.onReceiveValue(null);
//                                filePathCallbackLollipop = null;
//                            }
//                            filePathCallbackLollipop = filePathCallback;
//
//                            boolean isCapture = fileChooserParams.isCaptureEnabled();
//                            runCamera(isCapture);
//
//                            return true;
//                        }
//
//
//                        public void onProgressChanged(WebView view, int progress) {
//                            //  mProgressHorizontal.setProgress(progress);
//                        }
//
//
//                        private File createImageFile() throws IOException {
//                            // Create an image file name
//                            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
//                            String imageFileName = "JPEG_" + timeStamp + "_";
//                            File storageDir = Environment.getExternalStoragePublicDirectory(
//                                    Environment.DIRECTORY_PICTURES);
//                            File imageFile = File.createTempFile(
//                                    imageFileName,  /* prefix */
//                                    ".jpg",         /* suffix */
//                                    storageDir      /* directory */
//                            );
//                            return imageFile;
//                        }
//
//
//                    });//setwebchromeclient 끝
//
//                    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
//                    transport.setWebView(newWebView);
//                    resultMsg.sendToTarget();
//
//
//                    newWebView.setWebViewClient(new WebViewClient() {
//
//                        @Override
//                        public boolean shouldOverrideUrlLoading(WebView view, String url) {
//
//                            try {
//                                Log.d(TAG, "here2=" + url);
//                                popProgress.setVisibility(View.VISIBLE);
//                                String INTENT_PROTOCOL_START = "intent:";
//                                String INTENT_PROTOCOL_INTENT = "#Intent;";
//                                String INTENT_PROTOCOL_END = ";end;";
//                                String GOOGLE_PLAY_STORE_PREFIX = "market://details?id=";
//
//                                if (url.startsWith(INTENT_PROTOCOL_START)) {
//                                    final int customUrlStartIndex = INTENT_PROTOCOL_START.length();
//                                    final int customUrlEndIndex = url.indexOf(INTENT_PROTOCOL_INTENT);
//                                    if (customUrlEndIndex < 0) {
//                                        return false;
//                                    } else {
//                                        final String customUrl = url.substring(customUrlStartIndex, customUrlEndIndex);
//                                        try {
//                                            startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(customUrl)));
//                                        } catch (ActivityNotFoundException e) {
//                                            final int packageStartIndex = customUrlEndIndex + INTENT_PROTOCOL_INTENT.length();
//                                            final int packageEndIndex = url.indexOf(INTENT_PROTOCOL_END);
//
//                                            final String packageName = url.substring(packageStartIndex, packageEndIndex < 0 ? url.length() : packageEndIndex);
//                                            // startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName)));
//                                            // callProgram(url,getApplicationContext(),"com.ddd.gachita");
//                                            return url_scheme_intent(view, url);
//                                        }
//                                        return true;
//                                    }
//                                } else if (url.contains("com.mhows.giftishow")) {
//                                    callProgram(url, getApplicationContext(), "com.mhows.giftishow");
//                                    return true;
//                                } else if (url.contains("com.ddd.taxiking")) {
//                                    callProgram(url, getApplicationContext(), "com.ddd.taxiking");
//                                    return true;
//                                } else if (url.startsWith("http://qr.kakao.com/")) {
//                                    callProgram(url, getApplicationContext(), "com.kakao.talk");
//                                    return true;
//                                }/*
//                        else if (!url.startsWith("https://www.sslifessum.co.kr")&& !url.startsWith("http://sm.sslifessum.co.kr")) {
//                            callChrome(url, getApplicationContext());
//                            isPageOpen = false;
//                            popWindow.startAnimation(translateRightAnim);
//                            return true;
//                        }*/ else if (url.contains("youtube.com")) {
//                                    //startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//                                    callChrome(url, getApplicationContext());
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//                                    return true;
//                                } else if (url.startsWith("http://plus.kakao.com/home/")) {
//                                    //startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
//                                    callChrome(url, getApplicationContext());
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//                                    return true;
//                                } else if (url.startsWith("tg:")) {
//                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                                            .parse(url)));
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//                                    return true;
//                                } else if (url.startsWith("market://")) {
//                                    Log.d(TAG, "here44=" + url);
//
//                                    callChrome(url, getApplicationContext());
//                                    isPageOpen = false;
//                                    if (popWindow != null)
//                                        popWindow.startAnimation(translateRightAnim);
//
//                                    return true;
//                                } else if (url.startsWith("bandapp://")) {
//                                    Log.d(TAG, "here4=" + url);
//
//                                    callChrome(url, getApplicationContext());
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//
//                                    return true;
//                                } else if (url.startsWith("mailto:")) {
//                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                                            .parse(url)));
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//                                    return true;
//                                } else if (url.startsWith("tel:")) {
//                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                                            .parse(url)));
//                                    isPageOpen = false;
//                                    popWindow.startAnimation(translateRightAnim);
//                                    return true;
//                                } else if (url.startsWith("intent:")) {
//
//                                    return url_scheme_intent(view, url);
//                                } else {
//
//                                    //if (url != "https://www.edumars.net/appclass") {
//                                        newWebView.loadUrl(url);
//
//                                    //}
//
//                                    //newWebView.loadUrl(url);
//                                    return true;
//                                }
//
//                            } catch (Exception e) {
//                                e.printStackTrace(); // Prints the full stack trace of the exception
//                            }
//
//                            return true;
//
//
//                        }
//
//                        @Override
//                        public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
//
//
//                            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//                            builder.setTitle(getResources().getString(R.string.app_name));
//                            builder.setIcon(R.mipmap.ic_launcher);
//                            builder.setMessage("ssl 인증서를 통해 보안접속을 하시겠습니까?");
//                            builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//
//                                    handler.proceed();
//                                    Toast toast = Toast.makeText(getApplicationContext(),
//                                            "보안접속 중", Toast.LENGTH_LONG);
//                                    toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
//                                    //  toast.show();
//
//                                }
//                            });
//                            builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialog, int which) {
//                                    handler.cancel();
//                                    Toast toast = Toast.makeText(getApplicationContext(),
//                                            "보안접속만 허용됩니다.재시작 후 수락해 주세요.", Toast.LENGTH_LONG);
//                                    toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
//                                    //   toast.show();
//                                    finish();
//                                }
//                            });
//                            builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
//                                @Override
//                                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
//                                    if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
//                                        handler.cancel();
//                                        dialog.dismiss();
//                                        return true;
//                                    }
//                                    return false;
//                                }
//                            });
//                            AlertDialog dialog = builder.create();
//                            //  dialog.show();
//
//                        }
//
//                        @Override
//                        public void onPageStarted(WebView view, String url, Bitmap favicon) {
//
//                            super.onPageStarted(view, url, favicon);
//
//                            popProgress.setVisibility(View.VISIBLE);
//
//                            //now_url = url;
//                            Log.d(TAG, "popup here3=" + url);
///*
//                        if (url.contains("https://nid.naver.com/oauth2.0/authorize?response_type=code")|| url.contains("https://docsole.co.kr/sns/naver/callback.php?code=")) {
//                            Log.d(TAG,"네이버콜백 도착 창닫기 작동");
//
//                      //      if(newWebView !=null) newWebView.setVisibility(View.GONE);
//                            if(newWebView !=null) newWebView.setVisibility(View.GONE);
//                            mContainer.removeView(popWindow);
//                            webView.loadUrl("javascript:navercallback_value('"+url+ "')");
//
//                        }*/
//                            if (url.startsWith("https://telegram.me/share")) {
//
//                                callChrome(url, getApplicationContext());
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                return;
//                            } else if (url.startsWith("https://m.facebook.com/")) {
//
//                                callChrome(url, getApplicationContext());
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                return;
//                            } else if (url.startsWith("https://partners.sazaxa.com/")) {
//
//                                callChrome(url, getApplicationContext());
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                return;
//                            } else if (url.contains("https://kauth.kakao.com/oauth/authorize?proxy=")) {
//
//                                Log.d(TAG, "카카오콜백 도착 창닫기 작동");
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                if (newWebView != null) newWebView.setVisibility(View.GONE);
//                                mContainer.removeView(popWindow);
//                                //      if(newWebView !=null) newWebView.setVisibility(View.GONE);
//
//                                webView.loadUrl("javascript:kakaocallback_value('" + url + "')");
//
//
//                            }
//                            if (url.contains("http://photoreborn.cafe24.com/happy_chating.php")) {
//                                bottomNavigationView.setVisibility(View.GONE);
//                                // mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
//                                Log.d(TAG, "happy_chating finded bottomNavigationView gone");
//                            } else {
//                                bottomNavigationView.setVisibility(View.GONE);
//                                //  mSwipeRefreshLayout.setVisibility(View.VISIBLE);
//                                Log.d(TAG, "happy_chating not found bottomNavigationView visible");
//                            }
//
//
//                            if (url != null && !url.equals("about:blank")) {
//                                if (url.startsWith("http://") || url.startsWith("https://")) {
//                                    if (url.contains("http://market.android.com") ||
//                                            url.contains("http://m.ahnlab.com/kr/site/download") ||
//                                            url.endsWith(".apk")) {
//                                        try {
//
//                                            url_scheme_intent(view, url);
//
//                                        } catch (ActivityNotFoundException e) {
//                                            //  LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
//                                        }
//                                    } else {
//                                        ///  view.loadUrl( url );
//                                        Log.d("bb", "팝업 여기지남");
//                                        // return false;
//                                    }
//                                } else if (url.startsWith("mailto:")) {
//                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                                            .parse(url)));
//                                    // return false;
//                                } else if (url.startsWith("tel:")) {
//                                    startActivity(new Intent(Intent.ACTION_VIEW, Uri
//                                            .parse(url)));
//                                    // return false;
//                                } else {
//                                    try {
//
//                                        url_scheme_intent(view, url);
//
//                                        // view.loadUrl("http://ebadatv.com/error.htm");
//                                    } catch (ActivityNotFoundException e) {
//                                        // LOG.e(LOG_TAG, "Error dialing " + url + ": " + e.toString());
//                                    }
//                                }
//                            }
//
//                            if (url.startsWith("bandapp://")) {
//
//                                callChrome(url, getApplicationContext());
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//
//                            } else if (url.startsWith("rtsp://")) {
//                                Log.d(TAG, "here4=" + url);
//
//                                isPageOpen = false;
//                                //	popWindow.startAnimation(translateRightAnim);
//                                callChrome(url, getApplicationContext());
//
//                            } else if (url.startsWith("http://plus.kakao.com/home/")) {
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                callChrome(url, getApplicationContext());
//                            } else if (url.startsWith("intent://screen_channel_home")) {//네이버 플레이인 경우
//
//                                url_scheme_intent(view, url);
//
//                                Log.d(TAG, "here4=" + url);
//
//
//                            } else if (url.startsWith("intent:kakaolink://")) {
//                                Log.d(TAG, "here3=" + url);
//                                isPageOpen = false;
//                                popWindow.startAnimation(translateRightAnim);
//                                try {
//                                    callChrome(url, getApplicationContext());
//                                } catch (ActivityNotFoundException e) {
//
//                                }
//                            }
//
//                        }
//
//                        public void onPageFinished(WebView view, String Url) {
//                            popProgress.setVisibility(View.GONE);
//                            //now_url = Url;
//
//                            // Log.d(TAG,now_url.toString());
//
//
//                        }
//
//
//                    });
//
//                    Log.d(TAG, "onCreateWindow2");   // never log
//
//                }
//                catch(Exception e) {
//                    e.printStackTrace(); // Prints the full stack trace of the exception
//                }
//
//                return true;
//
//
//            }

            private Handler mHandler = new Handler() {

                @Override
                public void handleMessage(Message msg) {
                    // Get link-URL.
                    String url = (String) msg.getData().get("url");

                    // Do something with it.
                    Log.d(TAG, url + ":this SRC_ANCHOR_TYPE  src");
                    callChrome(url, getApplicationContext());
                }
            };

            @Override

            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(getResources().getString(R.string.app_name))
                        .setIcon(R.mipmap.ic_launcher)
                        .setMessage(message)
                        .setPositiveButton(android.R.string.ok,
                                new AlertDialog.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        result.confirm();
                                    }
                                })

                        .setCancelable(false)
                        .create()
                        .show();
                return true;

            }

            public boolean onJsConfirm(WebView view, String url,
                                       String message, final JsResult result) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle(getResources().getString(R.string.app_name))
                        .setMessage(message)
                        .setIcon(R.mipmap.ic_launcher)
                        .setPositiveButton(android.R.string.ok,
                                new AlertDialog.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        result.confirm();
                                    }
                                })
                        .setNegativeButton(android.R.string.cancel,
                                new AlertDialog.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog,
                                            int which) {
                                        result.cancel();
                                    }
                                }).setCancelable(false).create().show();
                return true;
            }


        });


        webView.setDownloadListener(new DownloadListener() {

            @SuppressLint("DefaultLocale")

            @Override


            public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
                DownloadManager dm;

                DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

                MimeTypeMap mimetype_now = MimeTypeMap.getSingleton();

                String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
                //downloadFileAsync(url, fileName);
                Log.d(TAG, fileName);
                String mimeType = mimetype_now.getMimeTypeFromExtension(fileName);
                fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toLowerCase();


                // request.setMimeType(mimetype);
                request.setMimeType("application/" + fileExtension);
                //------------------------COOKIE!!------------------------
                String cookies = CookieManager.getInstance().getCookie(url);
                request.addRequestHeader("cookie", cookies);
                //------------------------COOKIE!!------------------------
                request.addRequestHeader("User-Agent", userAgent);
                request.setDescription(getResources().getString(R.string.app_name));
                request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
                request.allowScanningByMediaScanner();
                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
                dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

                try {
                    dm.enqueue(request);
                } catch (Exception e) {
                    // if(Build.VERSION.SDK_INT >= 23)
                    //    checkPermission();
                }

            }

        });


        webView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {

                String userName = null;
                String userPass = null;

                if (handler.useHttpAuthUsernamePassword() && view != null) {
                    String[] haup = view.getHttpAuthUsernamePassword(host, realm);
                    if (haup != null && haup.length == 2) {
                        userName = haup[0];
                        userPass = haup[1];
                    }
                }

                if (userName != null && userPass != null) {
                    handler.proceed(userName, userPass);
                } else {
                    showHttpAuthDialog(view, handler, host, realm);
                }
            }

            private void showHttpAuthDialog(final WebView webview, final HttpAuthHandler handler, final String host, final String realm) {
                Context xmContext;
                xmContext = MainActivity.this;
                LayoutInflater factory = LayoutInflater.from(xmContext);
                final View textEntryView = factory.inflate(R.layout.basicauth_form, null);

                final androidx.appcompat.app.AlertDialog.Builder mHttpAuthDialog = new androidx.appcompat.app.AlertDialog.Builder(xmContext);
                mHttpAuthDialog.setTitle(realm).setView(textEntryView).setCancelable(false);
                mHttpAuthDialog.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        EditText etUserName = (EditText) textEntryView.findViewById(R.id.username_inputed);
                        String userName = etUserName.getText().toString();
                        EditText etUserPass = (EditText) textEntryView.findViewById(R.id.userpass_inputed);
                        String userPass = etUserPass.getText().toString();
                        webview.setHttpAuthUsernamePassword(host, realm, userName, userPass);
                        handler.proceed(userName, userPass);
                    }
                });
                mHttpAuthDialog.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                        webview.goBack();
                        handler.cancel();
                    }
                });

                mHttpAuthDialog.create().show();
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                //  mProgressHorizontal.setVisibility(View.VISIBLE);
            }


            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

                super.onPageStarted(view, url, favicon);
                ///    mSwipeRefreshLayout.setRefreshing(true);
           //     now_url = url;


                if (url.contains("http://photoreborn.cafe24.com/happy_chating.php")) {
                    bottomNavigationView.setVisibility(View.GONE);
                    //  mSwipeRefreshLayout.setVisibility(View.INVISIBLE);
                    Log.d(TAG, "happy_chating finded bottomNavigationView gone");
                } else {
                    bottomNavigationView.setVisibility(View.GONE);
                    //   mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                    Log.d(TAG, "happy_chating not found bottomNavigationView visible");
                }


                Log.d(TAG, url.toString() + " << url  on page started");
            }

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {


                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(getResources().getString(R.string.app_name));
                builder.setIcon(R.mipmap.ic_launcher);
                builder.setMessage("인증서에 문제가 있습니다.무시하고 계속 진행을 하시겠습니까?");
                builder.setPositiveButton("예", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        handler.proceed();
                        Toast toast = Toast.makeText(context,
                                "무시하고 접속 중", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
                        //    toast.show();

                    }
                });
                builder.setNegativeButton("아니오", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        handler.cancel();
                        Toast toast = Toast.makeText(context,
                                "보안접속만 허용됩니다.재시작 후 수락해 주세요.", Toast.LENGTH_LONG);
                        toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER, 0, 0);
                        //     toast.show();
                        //     finish();
                    }
                });
                builder.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                            handler.cancel();
                            dialog.dismiss();
                            return true;
                        }
                        return false;
                    }
                });
                AlertDialog dialog = builder.create();
                //  dialog.show();

            }

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

                //   view.loadUrl("file:///android_asset/index.html");
                Log.d(TAG, errorCode + " dis");


                switch (errorCode) {

                    case ERROR_AUTHENTICATION:               // 서버에서 사용자 인증 실패
                    case ERROR_BAD_URL:                            // 잘못된 URL
                    case ERROR_CONNECT:                           // 서버로 연결 실패

                        break;
                    case ERROR_FAILED_SSL_HANDSHAKE:     // SSL handshake 수행 실패
                    case ERROR_FILE:                                   // 일반 파일 오류
                    case ERROR_FILE_NOT_FOUND:                // 파일을 찾을 수 없습니다
                    case ERROR_HOST_LOOKUP:            // 서버 또는 프록시 호스트 이름 조회 실패
                    case ERROR_IO:                               // 서버에서 읽거나 서버로 쓰기 실패
                    case ERROR_PROXY_AUTHENTICATION:    // 프록시에서 사용자 인증 실패
                    case ERROR_REDIRECT_LOOP:                // 너무 많은 리디렉션
                    case ERROR_TIMEOUT:                          // 연결 시간 초과
                    case ERROR_TOO_MANY_REQUESTS:            // 페이지 로드중 너무 많은 요청 발생
                    case ERROR_UNKNOWN:                         // 일반 오류
                    case ERROR_UNSUPPORTED_AUTH_SCHEME:  // 지원되지 않는 인증 체계
                    case ERROR_UNSUPPORTED_SCHEME:

                        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                        //      builder.setTitle(R.string.ALRET_DIALOG_TITLE);
                        builder.setPositiveButton("확인", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                activity.finish();
                            }
                        });
                        builder.setMessage("네트워크 상태가 원활하지 않습니다. 잠시 후 다시 시도해 주세요.");
                        builder.show();

                        break;          // URI가 지원되지 않는 방식
                }
            }

            @Override
            public void doUpdateVisitedHistory(WebView view,
                                               String url,
                                               boolean isReload) {
                Log.d("bb", url + "<<doUpdateVisitedHistory");
                now_back_url = url;
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                try {
                    ///    Log.d(TAG, url.toString() + " :uristring");
                    String INTENT_PROTOCOL_START = "intent:";
                    String INTENT_PROTOCOL_INTENT = "#Intent;";
                    String INTENT_PROTOCOL_END = ";end;";
                    String GOOGLE_PLAY_STORE_PREFIX = "market://details?id=";
                    if (url.startsWith(INTENT_PROTOCOL_START)) {
                        final int customUrlStartIndex = INTENT_PROTOCOL_START.length();
                        final int customUrlEndIndex = url.indexOf(INTENT_PROTOCOL_INTENT);
                        if (customUrlEndIndex < 0) {
                            return false;
                        } else {
                            final String customUrl = url.substring(customUrlStartIndex, customUrlEndIndex);
                            try {
                                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(customUrl)));
                            } catch (ActivityNotFoundException e) {
                                final int packageStartIndex = customUrlEndIndex + INTENT_PROTOCOL_INTENT.length();
                                final int packageEndIndex = url.indexOf(INTENT_PROTOCOL_END);

                                final String packageName = url.substring(packageStartIndex, packageEndIndex < 0 ? url.length() : packageEndIndex);
                                //  startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName)));
                                return url_scheme_intent(view, url);
                            }
                            return true;
                        }
                    } else if (url.startsWith(GOOGLE_PLAY_STORE_PREFIX)) {//"market://details?id=com.kakao.talk"//url 값이 << 동일할때.마켓이동
                        Intent iz;
                        iz = new Intent(Intent.ACTION_VIEW);
                        iz.setData(Uri.parse(url));
                        startActivity(iz);
                        return true;
                    } else if (url.startsWith("tg:")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri
                                .parse(url)));
                        isPageOpen = false;
                        popWindow.startAnimation(translateRightAnim);
                        return true;
                    } else if (url.startsWith("ispmobile")) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                        return true;
                    } else if (url.contains("com.mhows.giftishow")) {
                        callProgram(url, getApplicationContext(), "com.mhows.giftishow");
                        return true;
                    } else if (url.contains("com.ddd.taxiking")) {
                        callProgram(url, getApplicationContext(), "com.ddd.taxiking");
                        return true;
                    } else if (url.contains("com.ddd.gachita")) {
                        callProgram(url, getApplicationContext(), "com.ddd.gachita");
                        return true;
                    } else if (url.startsWith("http://qr.kakao.com/")) {
                        callProgram(url, getApplicationContext(), "com.kakao.talk");
                        return true;
                    } else if (url.startsWith("tel:") || url.startsWith("sms:") || url.startsWith("mailto:")) {

                        Intent iz;
                        iz = new Intent(Intent.ACTION_VIEW);
                        iz.setData(Uri.parse(url));
                        startActivity(iz);
                        return true;
                    } else if (url.startsWith("tmap://")) {
                        Log.d(TAG, "here tmap:// called =" + url);
                        callProgram(url, getApplicationContext(), "com.skt.tmap.ku");

                        return true;
                    } else if (url.startsWith("market://")) {
                        Log.d(TAG, "here market:// called =" + url);
                        callChrome(url, getApplicationContext());

                        return true;
                    } else if (url.startsWith(getResources().getString(R.string.url_path) + "/" + "customer_myjubsu.php")) {
                        if (webView != null)
                            webView.clearCache(true);
                        view.loadUrl(url);

                    } else {

                        if (is기존코드사용안함여부 == true){  // paik기존 코드 사용안함

                        }
                        else {

                            view.loadUrl(url);

                        }

                    }

                }
                catch(Exception e) {
                    e.printStackTrace(); // Prints the full stack trace of the exception
                }

                return false;
            }

            // 페이지 로딩 종료시 호출
            @Override
            public void onPageFinished(WebView view, String Url) {

//                // paik 주소 저장
//                if (urlHistory.isEmpty() || !url.equals(urlHistory.peek())) {
//                    String urlStr = Url.toString();
//                    urlHistory.push(urlStr);
//                }

                // mProgressHorizontal.setVisibility(View.GONE);
                //  now_url = Url;
                super.onPageFinished(view, Url);

                if (weblink != null) {
                    weblink = null;
                    editor.putString("weblink", null);
                    editor.commit();
                }

                ///    mSwipeRefreshLayout.setRefreshing(false);

                 /* NOTICE 로그인을 한 다음 앱을 종료하고, 다시 앱을 실행했을 때 간헐적으로 로그인이 안 된 상태가 된다.
             이는 웹뷰의 RAM과 영구 저장소 사이에 쿠키가 동기화가 안 되어 있기 때문이다. 따라서 강제로 동기화를 해준다. */
                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
                    //noinspection deprecation
                    CookieSyncManager.getInstance().sync();
                } else {
                    // 롤리팝 이상에서는 CookieManager의 flush를 하도록 변경됨.
                    CookieManager.getInstance().flush();
                }


                //  mProgressHorizontal.setVisibility(View.GONE);
                if (IsClear) {
                    if (webView != null) {
                        webView.post(new Runnable() {//클리어 히스토리는 여기선느 작동하지 않는다. onpagefinish 에서 처리해야 한다
                            @Override
                            public void run() {
                                webView.clearHistory();

                            }
                        });
                    }
                    IsClear = false;
                }

            }
        }); //


    } //oncreate end


    private void runCamera(boolean _isCapture) {

        Log.d(TAG, "_isCapture = " + _isCapture);
        if (!_isCapture) {// 갤러리 띄운다.
            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setType(MediaStore.Images.Media.CONTENT_TYPE);
            pickIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            String pickTitle = "사진 가져올 방법을 선택하세요.";
            Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);
            return;
        }

        Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        File path = getFilesDir();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName = timeStamp + ".PNG";
        File file = new File(path, imageFileName);


        // File 객체의 URI 를 얻는다.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            String strpa = getPackageName();
            cameraImageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
        } else {
            cameraImageUri = Uri.fromFile(file);
        }
        //   intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);

        if (!_isCapture) { // 선택팝업 카메라, 갤러리 둘다 띄우고 싶을 때..
            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setType(MediaStore.Images.Media.CONTENT_TYPE);
            pickIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            String pickTitle = "사진 가져올 방법을 선택하세요.";
            Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);

            // 카메라 intent 포함시키기..
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{intentCamera});
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);
        } else {// 바로 카메라 실행..
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");

            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
            intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , new Parcelable[]{intentCamera});

            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);


        }
    }

    private File createImageFile() throws IOException {
        // Create an image file name

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES);
        File imageFile = File.createTempFile(
                imageFileName,  /* prefix */
                ".png",         /* suffix */
                storageDir      /* directory */
        );


        return imageFile;
    }


/*
    private void runCamera(boolean _isCapture)
    {

        Log.d(TAG,"_isCapture = "+_isCapture);
        if (!_isCapture)
        {// 갤러리 띄운다.
            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setType(MediaStore.Images.Media.CONTENT_TYPE);
            pickIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            String pickTitle = "사진 가져올 방법을 선택하세요.";
            Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);
            return;
        }

        Intent intentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        File path = getFilesDir();
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        imageFileName =  timeStamp + ".PNG";
        File file = new File(path, imageFileName);


        // File 객체의 URI 를 얻는다.
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            String strpa = getPackageName();
            cameraImageUri = FileProvider.getUriForFile(this, getPackageName() + ".fileprovider", file);
        }
        else
        {
            cameraImageUri = Uri.fromFile(file);
        }


        if (!_isCapture)
        { // 선택팝업 카메라, 갤러리 둘다 띄우고 싶을 때..
            Intent pickIntent = new Intent(Intent.ACTION_PICK);
            pickIntent.setType(MediaStore.Images.Media.CONTENT_TYPE);
            pickIntent.setData(MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            String pickTitle = "사진 가져올 방법을 선택하세요.";
            Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);

            // 카메라 intent 포함시키기..
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[]{intentCamera});
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);
        }
        else
        {// 바로 카메라 실행..
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");

            // Create file chooser intent
            Intent chooserIntent = Intent.createChooser(i, "Image Chooser");
            intentCamera.putExtra(MediaStore.EXTRA_OUTPUT, cameraImageUri);
            // Set camera intent to file chooser
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS
                    , new Parcelable[] { intentCamera });

            // On select image call onActivityResult method of activity
            startActivityForResult(chooserIntent, FILECHOOSER_LOLLIPOP_REQ_CODE);


        }
    }*/

    private void MyPushCustomAlertDialog() {

        final Dialog MyDialog = new Dialog(MainActivity.this);
        MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        MyDialog.setContentView(R.layout.customdialog);
        MyDialog.setTitle("메시지");
        MyDialog.setCancelable(false);
        MyDialog.getWindow().getAttributes().windowAnimations = R.style.DialogSlide;

        Button hello = (Button) MyDialog.findViewById(R.id.hello);
        Button close = (Button) MyDialog.findViewById(R.id.close);
        TextView tv_subject = (TextView) MyDialog.findViewById(R.id.tv_subject);
        TextView tv_message = (TextView) MyDialog.findViewById(R.id.tv_message);
        TextView tv_weblink = (TextView) MyDialog.findViewById(R.id.tv_weblink);
        img = (ImageView) MyDialog.findViewById(R.id.img);
        tv_subject.setText(subject);
        tv_message.setText(p_messsage);
        tv_weblink.setText(weblink);
        Log.d(TAG, "imgUrl<==>" + imgUrl);
        if (imgUrl != null) img.setImageBitmap(imgBitmap);
        else img.setVisibility(View.GONE);
        hello.setEnabled(true);
        close.setEnabled(true);


        hello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(), "Hello, I'm Custom Alert Dialog", Toast.LENGTH_LONG).show();
                MyDialog.dismiss();
                finish();
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.cancel();

            }
        });

        //   MyDialog.show();// 히든 처리 // 추가코드

        message_found = false;
        editor.putString("p_messsage", null);
        editor.putString("subject", null);
        editor.putString("weblink", null);
        editor.putString("imgUrl", null);
        editor.putString("arg1", null);
        editor.putBoolean("message_found", false);//추가코드
        editor.commit();
    }


    private void MyCustomAlertDialog() {

        final Dialog MyDialog = new Dialog(MainActivity.this);
        MyDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        MyDialog.setContentView(R.layout.customdialog_push_question);
        MyDialog.setTitle("메시지");
        MyDialog.setCancelable(false);
        MyDialog.getWindow().getAttributes().windowAnimations = R.style.DialogSlide;

        Button hello = (Button) MyDialog.findViewById(R.id.hello);
        Button close = (Button) MyDialog.findViewById(R.id.close);

        hello.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Toast.makeText(getApplicationContext(), "Hello, I'm Custom Alert Dialog", Toast.LENGTH_LONG).show();
                //finish();
                //미동의
                editor.putBoolean("ad_push_value", false);
                editor.commit();
                MyDialog.dismiss();
            }
        });
        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyDialog.cancel();
                Log.d("bb", "dialog agreed");
                //동의
                editor.putBoolean("ad_push_value", true);
                editor.commit();

                long now = System.currentTimeMillis();
                Date date = new Date(now);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                String getTime = sdf.format(date);
                Toast.makeText(getApplicationContext(), getTime + "에 수신동의 처리 되었습니다", Toast.LENGTH_LONG).show();
            }
        });

        MyDialog.show();
    }


    private boolean url_scheme_intent(WebView view, String url) {
        Log.d(TAG, "url_scheme_intent");
        Log.d(SampleApplication.m_strLogTag, "[PayDemoActivity] called__test - url=[" + url + "]");

        //chrome 버젼 방식 : 2014.01 추가
        if (url.startsWith("intent")) {
            //ILK 용
            if (false /*url.contains( "com.lotte.lottesmartpay" ) */) {
                try {
                    startActivity(Intent.parseUri(url, Intent.URI_INTENT_SCHEME));
                } catch (URISyntaxException e) {
                    Log.d(SampleApplication.m_strLogTag, "[PayDemoActivity] URISyntaxException=[" + e.getMessage() + "]");
                    return false;
                } catch (ActivityNotFoundException e) {
                    Log.d(SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]");
                    return false;
                }
            }
//	            //ILK 용 -- 삭제 처리
//	            else if ( url.contains( "com.ahnlab.v3mobileplus" ) )
//	            {
//	                try {
//	                    view.getContext().startActivity(Intent.parseUri(url, 0));
//	                } catch ( URISyntaxException        e ) {
//	                    Log.d( SampleApplication.m_strLogTag, "[PayDemoActivity] URISyntaxException=[" + e.getMessage() + "]" );
//	                    return false;
//	                } catch ( ActivityNotFoundException e ) {
//	                    Log.d( SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]" );
//	                    return false;
//	                }
//	            }
            //폴라리스 용
            else {
                Intent intent = null;

                try {
                    intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);
                } catch (URISyntaxException ex) {
                    Log.d(SampleApplication.m_strLogTag, "[PayDemoActivity] URISyntaxException=[" + ex.getMessage() + "]");
                    return false;
                }


                // 앱설치 체크를 합니다. 안드로이드11 대응

                if (!isPackageInstalled(intent.getPackage(), context.getPackageManager())) {
                    String packagename = intent.getPackage();

                    if (packagename != null) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + packagename)));

                        return true;
                    }

                }


                // 앱설치 체크를 합니다.안드로이드 10까지 활성화 코드
//                if ( getActivity().getPackageManager().resolveActivity( intent, 0 ) == null )
//                {
//                    String packagename = intent.getPackage();
//
//                    if ( packagename != null )
//                    {
//                        startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse( "market://search?q=pname:" + packagename ) ) );
//
//                        return true;
//                    }
//                }
//
//                intent = new Intent( Intent.ACTION_VIEW, Uri.parse( intent.getDataString() ) );
//안드로이드10까지 활성화 코드 끝
                try {
                    startActivity(intent);

                } catch (ActivityNotFoundException e) {
                    Log.d(SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]");
                    String packagename = intent.getPackage();
                    if (packagename != null) {
                        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pname:" + packagename)));

                        return true;
                    }
                    return false;
                }


//안드로이드 10까지 아래코드 활성화였다
//                try{
//                    startActivity( intent );
//                }catch( ActivityNotFoundException e ) {
//                    Log.d( SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]" );
//                    return false;
//                }


            }
        }
        // 기존 방식
        else {
            if (url.startsWith("ispmobile")) {
                if (!new PackageState(this).getPackageDownloadInstallState("kvp.jjy.MispAndroid")) {
                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=kvp.jjy.MispAndroid320")));

                    return true;
                }
            } else if (url.startsWith("paypin")) {
                if (!new PackageState(this).getPackageDownloadInstallState("com.skp.android.paypin")) {
                    if (!url_scheme_intent(view, "tstore://PRODUCT_VIEW/0000284061/0")) {
                        url_scheme_intent(view, "market://details?id=com.skp.android.paypin&feature=search_result#?t=W251bGwsMSwxLDEsImNvbS5za3AuYW5kcm9pZC5wYXlwaW4iXQ.k");
                    }

                    return true;
                }
            }

            // 삼성과 같은 경우 어플이 없을 경우 마켓으로 이동 할수 있도록 넣은 샘플 입니다.
            // 실제 구현시 업체 구현 여부에 따라 삭제 처리 하시는것이 좋습니다.
            if (url.startsWith("mpocket.online.ansimclick")) {
                if (!new PackageState(this).getPackageDownloadInstallState("kr.co.samsungcard.mpocket")) {
                    Toast.makeText(this, "어플을 설치 후 다시 시도해 주세요.", Toast.LENGTH_LONG).show();

                    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=kr.co.samsungcard.mpocket")));

                    return true;
                }
            }

            try {
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            } catch (Exception e) {
                // 어플이 설치 안되어 있을경우 오류 발생. 해당 부분은 업체에 맞게 구현
                Toast.makeText(this, "해당 어플을 설치해 주세요.", Toast.LENGTH_LONG).show();

                if (url.contains("tstore://")) {
                    return false;
                }
            }
        }

        return true;
    }


    //추가된 함수
    public void updateIconBadgeCount(Context context, int count) {

        Intent intent = new Intent("android.intent.action.BADGE_COUNT_UPDATE");

        // Component를 정의
        intent.putExtra("badge_count_package_name", context.getPackageName());
        intent.putExtra("badge_count_class_name", getLauncherClassName(context));

        // 카운트를 넣어준다.
        intent.putExtra("badge_count", count);

        // Version이 3.1이상일 경우에는 Flags를 설정하여 준다.
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.GINGERBREAD_MR1) {
            //intent.setFlags(0x00000020);
        }

        // send
        sendBroadcast(intent);
    }

    private String getLauncherClassName(Context context) {

        String result = "";
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.setPackage(getPackageName());

        List<ResolveInfo> resolveInfoList = getPackageManager().queryIntentActivities(intent, 0);
        if (resolveInfoList != null && resolveInfoList.size() > 0) {
            Log.d(TAG, "getpackagemanager");
            return resolveInfoList.get(0).activityInfo.name;
        }
        Log.d(TAG, "no getpackagemanager");
        return result;// 널값이 들어간다
    }
    //추가된 함수 끝. 뱃지 업데이트


    @Override
    public void onBackPressed() {
        try {
            if (isPageOpen) {
                // 팝업이 열려있으면 먼저 팝업을 닫음
                isPageOpen = false;
                popWindow.startAnimation(translateRightAnim);
            } else if (webView != null) {
                String currentUrl = getCurrentBaseUrl() ; // webView.getUrl();
                
                // 현재 URL이 edumars.net이 아닌 경우
                if (currentUrl != null && !currentUrl.equals("https://edumars.net/")) {
                    // 이전 페이지가 있으면 이전 페이지로 이동, 없으면 메인으로
                    if (webView.canGoBack()) {
                        // 웹뷰에서 이전 페이지로 이동
                        webView.goBack();
                    } else {
                        // 이전 페이지가 없으면 메인으로 이동
                        webView.loadUrl("https://edumars.net/");
                    }
                } 
                // edumars.net인 경우에만 일반적인 뒤로가기 처리
                else if (webView.canGoBack() && !currentUrl.equals("https://edumars.net/")) {
                    // 웹뷰 이전 페이지로 이동 전에 현재 urlHistory에서 현재 URL 제거
                    if (!urlHistory.isEmpty()) {
                        String historyUrl = urlHistory.pop(); // 현재 URL 제거
                        Log.d(TAG, "URL 히스토리에서 제거: " + historyUrl + ", 남은 항목: " + urlHistory.size());
                    }
                    
                    // 웹뷰에서 이전 페이지로 이동

                    webView.goBack();
                } else {
                    if (doubleBackToExitPressedOnce) {
                        backButtonHandler.removeCallbacks(backButtonRunnable);
                        finish();
                    } else {
                        doubleBackToExitPressedOnce = true;
                        Toast.makeText(this, "한 번 더 누르면 종료됩니다", Toast.LENGTH_SHORT).show();
                        backButtonHandler.postDelayed(backButtonRunnable, 2000);
                    }
                }
            } else {
                super.onBackPressed();
            }
        } catch (Exception e) {
            // 예외 발생 시 로그 출력 및 안전하게 처리
            Log.e(TAG, "onBackPressed 오류: " + e.getMessage());
            e.printStackTrace();
            
            // 예외 발생 시 기본 동작 수행
            try {
                if (doubleBackToExitPressedOnce) {
                    finish();
                } else {
                    doubleBackToExitPressedOnce = true;
                    Toast.makeText(this, "한 번 더 누르면 종료됩니다", Toast.LENGTH_SHORT).show();
                    backButtonHandler.postDelayed(backButtonRunnable, 2000);
                }
            } catch (Exception ex) {
                // 최후의 방어, 앱 종료
                finish();
            }
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
       /* if (id == R.id.action_settings) {
            return true;
        }*/

        return super.onOptionsItemSelected(item);
    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode,
//                                    Intent intent) {
//        super.onActivityResult(requestCode, resultCode, intent);
//        //  Log.d(TAG,requestCode+" resultcode");
//        if (requestCode == FILECHOOSER_RESULTCODE) {
//            if (null == mUploadMessage)
//                return;
//            Uri result = intent == null || resultCode != RESULT_OK ? null
//                    : intent.getData();
//            mUploadMessage.onReceiveValue(result);
//            mUploadMessage = null;
//
//        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//            if (requestCode == FILECHOOSER_LOLLIPOP_REQ_CODE) {
//                Log.d(TAG, filePathCallbackLollipop + " = filePathCallbackLollipop");
//                Uri[] result = new Uri[0];
//                if (filePathCallbackLollipop == null) return;
//            /*    filePathCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, intent));
//                filePathCallbackLollipop = null;*/
//
//                if (resultCode == RESULT_OK) {
//                    result = (intent == null) ? new Uri[]{mCapturedImageURI} : WebChromeClient.FileChooserParams.parseResult(resultCode, intent);
//                }
//                filePathCallbackLollipop.onReceiveValue(result);
//            }
//        }
//
//    }


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case FILECHOOSER_NORMAL_REQ_CODE:
                if (resultCode == RESULT_OK) {
                    if (filePathCallbackNormal == null) return;
                    Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
                    filePathCallbackNormal.onReceiveValue(result);
                    filePathCallbackNormal = null;
                }
                break;
            case FILECHOOSER_LOLLIPOP_REQ_CODE:
                if (resultCode == RESULT_OK) {
                    if (filePathCallbackLollipop == null) return;
                    if (data == null)
                        data = new Intent();
                    if (data.getData() == null)
                        data.setData(cameraImageUri);

                    filePathCallbackLollipop.onReceiveValue(WebChromeClient.FileChooserParams.parseResult(resultCode, data));
                    filePathCallbackLollipop = null;
                } else {
                    if (filePathCallbackLollipop != null) {
                        filePathCallbackLollipop.onReceiveValue(null);
                        filePathCallbackLollipop = null;
                    }

                    if (filePathCallbackNormal != null) {
                        filePathCallbackNormal.onReceiveValue(null);
                        filePathCallbackNormal = null;
                    }
                }
                break;
            default:

                break;
        }


        super.onActivityResult(requestCode, resultCode, data);

    }

    @Override
    public void onPause() {
        super.onPause();
        //  _amanager.onPause(this);
            mFusedLocationClient.removeLocationUpdates(locationCallback);


        CookieSyncManager.getInstance().sync();
        IsAppOpened = false;
        unregisterReceiver(completeReceiver);

        try {
            Class.forName("android.webkit.WebView")
                    .getMethod("onPause", (Class[]) null)
                    .invoke(webView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void onDestory() {
        super.onDestroy();
        //  _amanager.onDestroy(this);
        mHandler.removeMessages(0);
        mHandler.removeCallbacksAndMessages(null);
        IsAppOpened = false;
        moveTaskToBack(true);
        finish();
        System.exit(0);
        Process.killProcess(Process.myPid());

    }

    //public static String getKeyHash(final Context context) {
    //    PackageInfo packageInfo = getPackageInfo(context, PackageManager.GET_SIGNATURES);
    //    if (packageInfo == null)
    //        return null;

    //    for (Signature signature : packageInfo.signatures) {
    //        try {
    //            MessageDigest md = MessageDigest.getInstance("SHA");
    //            md.update(signature.toByteArray());
    //            return Base64.encodeToString(md.digest(), Base64.NO_WRAP);
    //        } catch (NoSuchAlgorithmException e) {
    //            Log.w(TAG, "Unable to get MessageDigest. signature=" + signature, e);
    //        }
    //    }
    //    return null;
    //}

    @SuppressLint("MissingSuperCall")


    public void finishActivity(String p_strFinishMsg) {
        Intent intent = new Intent();

        if (p_strFinishMsg != null) {
            intent.putExtra(ACTIVITY_RESULT, p_strFinishMsg);

            setResult(RESULT_OK, intent);
        } else {
            setResult(RESULT_CANCELED);
        }

        //finish();
    }

    //@SuppressLint("MissingSuperCall")
    //@Override
    protected void onRestart2() {
        super.onResume();

   //     Log.d(SampleARpplication.m_strLogTag,                "[PayDemoActivity] called__onResume + INPROGRESS=[" + m_nStat + "]");

        if (webView != null)
            webView.post(new Runnable() {
                @Override
                public void run() {
                    Android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
                    token = prefs.getString("token", null);//추가된 코드
                    if (token != null)
                        webView.loadUrl("javascript:set_value('" + "" + "','" + Android_id + "','" + token + "','" + "saved_arg1" + "','" + "saved_arg2" + "','" + "saved_arg3" + "')");

                }
            });

        SampleApplication myApp = (SampleApplication) getApplication();

        if (myApp.m_uriResult != null) {
            if ((myApp.m_uriResult.getQueryParameter("isp_res_cd") == null ? "" :
                    myApp.m_uriResult.getQueryParameter("isp_res_cd")).equals("0000")) {
                Log.d(SampleApplication.m_strLogTag,
                        "[PayDemoActivity] ISP Result = 0000");
            } else {
                Log.d(SampleApplication.m_strLogTag,
                        "[PayDemoActivity] ISP Result = cancel");
            }
        }

        if (m_nStat == PROGRESS_STAT_IN) {
            checkFrom();

            myApp.b_type = false;
        }

        myApp.m_uriResult = null;


    }

    //메뉴 클릭시 이동
    public void btnStart(MenuItem v) {
        //여기에다 할 일을 적어주세요.
        switch (v.getItemId()) {
            case R.id.action_one:
                Log.d(TAG, "button1 pressed");
                webView.loadUrl(getResources().getString(R.string.home_url));
                MenuItem prevBottomNavigation = bottomNavigationView.getMenu().getItem(0);
                // prevBottomNavigation.setChecked(false);
                break;

            case R.id.action_three:
                webView.loadUrl(getResources().getString(R.string.recent_url));
                break;
            case R.id.action_four:
               /* Intent intent = new Intent(mContext, Received_listviewActivity.class);
                mContext.startActivity(intent);*/
                webView.loadUrl(getResources().getString(R.string.go_juckjung));
                break;
            case R.id.action_five:
              /*  Intent intent_setting = new Intent(mContext, SettingActivity.class);
                mContext.startActivity(intent_setting);*/

                Intent intent_push = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                intent_push.addCategory(Intent.CATEGORY_DEFAULT);
                //for Android 5-7
                intent_push.putExtra("app_package", getPackageName());
                intent_push.putExtra("app_uid", getApplicationInfo().uid);
                // for Android 8 and above
                intent_push.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());


                startActivity(intent_push);

                break;

        }

    }

    private void checkFrom() {
        try {
            SampleApplication myApp = (SampleApplication) getApplication();

            if (myApp.m_uriResult != null) {
                m_nStat = PROGRESS_DONE;

                String strResultInfo = myApp.m_uriResult.getQueryParameter("approval_key");

                if (strResultInfo == null || strResultInfo.length() <= 4)
                    finishActivity("ISP 결제 오류");

                String strResCD = strResultInfo.substring(strResultInfo.length() - 4);

                Log.d(SampleApplication.m_strLogTag,
                        "[PayDemoActivity] result=[" + strResultInfo + "]+" + "res_cd=[" + strResCD + "]");

                if (strResCD.equals("0000") == true) {
                    String strApprovalKey = "";

                    strApprovalKey = strResultInfo.substring(0, strResultInfo.length() - 4);

                    Log.d(SampleApplication.m_strLogTag,
                            "[PayDemoActivity] approval_key=[" + strApprovalKey + "]");

                    webView.loadUrl("https://devpggw.kcp.co.kr:8100/app.do?ActionResult=app&approval_key=" + strApprovalKey);
                    //mWebView.loadUrl( "https://smpay.kcp.co.kr/app.do?ActionResult=app&approval_key=" + strApprovalKey );
                } else if (strResCD.equals("3001") == true) {
                    //finishActivity( "ISP 결제 사용자 취소" );
                } else {
                    // finishActivity( "ISP 결제 기타 오류" );
                }
            }
        } catch (Exception e) {
        } finally {
        }
    }




    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // Checks the orientation of the screen
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //  Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            //    Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
            webView.setFocusable(true);
            webView.setFocusableInTouchMode(true);
            webView.requestFocus();
        }
    }

    @SuppressLint("MissingPermission")
    @Override
    public void onResume() {
        super.onResume();

        mFusedLocationClient.requestLocationUpdates(mLocationRequest, locationCallback, null);

        if (is기존코드사용안함여부 == true){  // paik기존 코드 사용안함

        }
        else {

            try {
                Log.d(TAG, "mainactivity onresume 실행됨 ");
                String url2 = prefs.getString("url", null);
                String param_intent_url = prefs.getString("param_intent_url", null);


                //   _amanager.onResume(this);
                mFusedLocationClient.requestLocationUpdates(mLocationRequest, locationCallback, null);
                if (webView != null) {
                    if (param_intent_url != null) {

                        webView.post(new Runnable() {
                            @Override
                            public void run() {


                                if (webView.canGoBack() == true) {

                                    int i = 0;

                                } else {

                                    int i = 1;

                                }

                                token = prefs.getString("token", null);//추가된 코드

                                String url211 = "";
                                if (token != null) {
                                    url211 = param_intent_url + "&regid=" + token;
                                } else {
                                    url211 = param_intent_url; // + "&regid=" + token;
                                }

                                SharedPreferences.Editor editor = MainActivity.prefs.edit();
                                editor.putString("param_intent_url", null);
                                editor.commit();

                                String param_intent_url2 = prefs.getString("param_intent_url", null);


                                //webView.loadUrl(url211);

                                //webView.loadUrl(url211);
                                //webView.loadUrl(url211);

                                //webView.evaluateJavascript("window.open('" + url211 + "', '_blank')", null);
                                //webView.saveState();

                                if (webView.canGoBack() == true) {

                                    int i = 0;

                                } else {

                                    int i = 1;

                                }


                                //Android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
                                //token = prefs.getString("token", null);//추가된 코드
                                //if (token != null)
                                //    webView.loadUrl("javascript:set_value('" + "" + "','" + Android_id + "','" + token + "','" + "saved_arg1" + "','" + "saved_arg2" + "','" + "saved_arg3" + "')");

                            }
                        });


                        //String url211 = param_intent_url + "&regid=" + token;
                        //MainActivity.webView.loadUrl(url211);


                    } else {

                        if (is기존코드사용안함여부 == true) {  // paik기존 코드 사용안함

                        } else {

                            if (is기존코드사용안함여부 == true) {  // paik기존 코드 사용안함

                            } else {

                                webView.post(new Runnable() {
                                    @Override
                                    public void run() {
                                        Android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
                                        token = prefs.getString("token", null);//추가된 코드
                                        if (token != null)
                                            webView.loadUrl("javascript:set_value('" + "" + "','" + Android_id + "','" + token + "','" + "saved_arg1" + "','" + "saved_arg2" + "','" + "saved_arg3" + "')");

                                    }
                                });

                            }

                        }
                    }


                }

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





            CookieSyncManager.getInstance().stopSync();
            // 앱이 실행되면 리시버 등록

            //        IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
            //
            //        // paik
            //        //registerReceiver(completeReceiver, completeFilter);
            //
            //        // Register receiver with the appropriate flag for different SDK versions
            //        if (Build.VERSION.SDK_INT >= 33) { // API 33 or higher
            //            registerReceiver(completeReceiver, completeFilter, Context.RECEIVER_NOT_EXPORTED);
            //        } else {
            //            registerReceiver(completeReceiver, completeFilter);
            //        }


        }

        try {
            Class.forName("android.webkit.WebView")
                    .getMethod("onResume", (Class[]) null)
                    .invoke(webView, (Object[]) null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CookieSyncManager.getInstance().stopSync();
        // 앱이 실행되면 리시버 등록

        IntentFilter completeFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);

        // Android 13(API 33) 이상에서는 RECEIVER_NOT_EXPORTED 플래그 필요
        if (Build.VERSION.SDK_INT >= 33) {
            registerReceiver(completeReceiver, completeFilter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            registerReceiver(completeReceiver, completeFilter);
        }

    }

    @Override
    public void onStart() {
        super.onStart();


        //   sensorManager.registerListener ( this,stepCountSensor,SensorManager.SENSOR_DELAY_GAME );
    }

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

    }

    @Override
    public void onNavigationItemReselected(@NonNull MenuItem menuItem) {

    }


    public class WebAppInterface2 {
        Context mContext;

        WebAppInterface2(Context c) {
            mContext = c;
        }


        @JavascriptInterface
        public void closewindow(String url) {
            Log.d("bb", " closewindow called");
            if (newWebView != null) {
                isPageOpen = false;
                popWindow.startAnimation(translateRightAnim);
                //   newWebView.setVisibility(View.GONE);
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        webView.loadUrl(url);
                    }
                });
            }
        }

    }

    public class WebAppInterface {
        Context mContext;


        /**
         * Instantiate the interface and set the context
         */
        WebAppInterface(Context c) {
            mContext = c;
        }

        /**
         * Show a toast from the web page
         */
        @JavascriptInterface
        public void showToast(String toast) {
            Toast.makeText(mContext, toast, Toast.LENGTH_LONG).show();
        }

        @JavascriptInterface
        public void qrcode_get_value() {
            Log.d("bb", " 오픈액티비티 호출 called");

            Intent intent = new Intent(getApplicationContext(), ReaderActivity.class);
            startActivity(intent);


        }

        @JavascriptInterface
        public void sns(String str1, String str) {
            Log.d(TAG, " sns value called");


            Intent intent = new Intent();
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            intent.putExtra(Intent.EXTRA_SUBJECT, str1);
            intent.putExtra(Intent.EXTRA_TEXT, str);
            Intent chooser = Intent.createChooser(intent, "공유");
            startActivity(chooser);

        }


        @JavascriptInterface
        public void ad_pushsetting(Boolean value) {
            Log.d(TAG, " ad push setting value called");
//            Intent intent = new Intent();
//            intent.setClass(getApplicationContext(), SettingActivity.class);
//            startActivity(intent);


            editor = prefs.edit();

            Log.d(TAG, "now_ad_push_value" + prefs.getBoolean("ad_push_value", false));
            ///   if(!prefs.getBoolean("ad_push_value", true))  {
            if (value) {
                Toast.makeText(mContext, "광고 푸시 수신 허용 설정되었습니다", Toast.LENGTH_LONG).show();
                editor.putBoolean("ad_push_value", true);
                editor.commit();

                long now = System.currentTimeMillis();
                Date date = new Date(now);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
                String getTime = sdf.format(date);
                Toast.makeText(getApplicationContext(), getTime + "에 수신동의 처리 되었습니다", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(mContext, "광고 푸시 수신 거부 설정되었습니다", Toast.LENGTH_LONG).show();
                editor.putBoolean("ad_push_value", false);
                editor.commit();
            }


        }

        @JavascriptInterface
        public void getManbogiVal() {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:manbogi_value('" + cnt + "')");
                }
            });
        }

        @JavascriptInterface
        public void get_now_url() {
            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:now_url_value('" + now_url + "')");
                }
            });
        }

        @JavascriptInterface
        public void nomal_push() {
            Log.d(TAG, " nomal_push called");
            webView.post(new Runnable() {
                @Override
                public void run() {

                    Intent intent_push = new Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS);
                    intent_push.addCategory(Intent.CATEGORY_DEFAULT);
                    //for Android 5-7
                    intent_push.putExtra("app_package", getPackageName());
                    intent_push.putExtra("app_uid", getApplicationInfo().uid);
                    // for Android 8 and above
                    intent_push.putExtra("android.provider.extra.APP_PACKAGE", getPackageName());


                    startActivity(intent_push);

                }
            });
        }


        @JavascriptInterface
        public void get_location() {
            Log.d(TAG, " get value called");
            locationControlTask = new LocationControl();
            locationControlTask.execute(mContext);
            final double lati = 0, longi = 0;

            Log.d(TAG, "접속시도");//위치
            if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    ActivityCompat#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for ActivityCompat#requestPermissions for more details.
                mFusedLocationClient.getLastLocation()
                        .addOnSuccessListener(MainActivity.this, new OnSuccessListener<Location>() {

                            @Override
                            public void onSuccess(Location location) {
                                // Got last known location. In some rare situations this can be null.
                                if (location != null) {

                                    // Logic to handle location object
                                    now_longi = location.getLongitude();
                                    now_lati = location.getLatitude();
                                    //  Log.d("Main", "longtitude=" + longi + ", latitude=" + lati);
                                    Log.d(TAG, "=위치정보는 위도 " + now_longi + " 경도 " + now_lati);
                                    webView.post(new Runnable() {
                                        @Override
                                        public void run() {//쓰레드로 작동.
                                                  Toast.makeText(MainActivity.this, "위도="+lati+"경도="+longi, Toast.LENGTH_SHORT).show();
                                            ///      webView.loadUrl("javascript:set_value_location('" + lati + "','" + longi + "')");
                                            //  webView.loadUrl("javascript:test('"+lati+"')");
                                            hasLocation = true;
                                        }
                                    });
                                }
                            }
                        }).addOnFailureListener(new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Log.d(TAG, "Error trying to get last GPS location");
                                Toast.makeText(MainActivity.this, "설정 > 위치정보를 사용함으로 설정해주세요!", Toast.LENGTH_LONG).show();
                                locationControlTask.dialog.dismiss();
                                e.printStackTrace();
                            }
                        });
                return;
            }


        }
//        @JavascriptInterface
//        public void get_value() {
//            Log.d(TAG, " get value called");
//            // Toast.makeText(mContext, "호출완료", Toast.LENGTH_LONG).show();
//            //  prefs = getSharedPreferences("pref", Context.MODE_PRIVATE);
//
//            final double lati = 0,longi=0;
//            webView.post(new Runnable() {
//                @Override
//                public void run() {
//
//                    webView.loadUrl("javascript:set_value('" + Str_MyPhoneNumber +"','" + Android_id + "','" + token + "')");
//
//                }
//            });
//        }


        @JavascriptInterface
        public void get_value() {
            Log.d(TAG, " get value called");

            final double lati = 0,longi=0;
            SharedPreferences.Editor editor = prefs.edit();
            final String saved_userid = prefs.getString("userid", "");
            final String saved_arg1 = prefs.getString("arg1", "");
            final String saved_arg2 = prefs.getString("arg2", "");
            final String saved_arg3 = prefs.getString("arg3", "");

            Log.d(TAG, saved_userid+"= get value called");

            webView.post(new Runnable() {
                @Override
                public void run() {
                    Android_id= Settings.Secure.getString(mContext.getContentResolver(),                Settings.Secure.ANDROID_ID);
                    token = prefs.getString("token", null);//추가된 코드
                    webView.loadUrl("javascript:set_value('"+saved_userid + "','" + Android_id + "','" + token+  "','" + saved_arg1+ "','" + saved_arg2+ "','" + saved_arg3 + "')");

                }
            });
        }

        @JavascriptInterface
        public void get_user_info() {
            Log.d(TAG, " get value called");

            final double lati = 0,longi=0;
           // SharedPreferences.Editor editor = prefs.edit();
            final String saved_userid = prefs.getString("userid", "");
            final String saved_email = prefs.getString("email", "");
            final String saved_nickname = prefs.getString("nickname", "");
            final String saved_arg1 = prefs.getString("arg1", "");
            final String saved_arg2 = prefs.getString("arg2", "");
            final String saved_arg3 = prefs.getString("arg3", "");

            Log.d(TAG, saved_userid+"= get value called");

            webView.post(new Runnable() {
                @Override
                public void run() {
                    Android_id= Settings.Secure.getString(mContext.getContentResolver(),                Settings.Secure.ANDROID_ID);
                    token = prefs.getString("token", null);//추가된 코드
                    webView.loadUrl("javascript:set_user_info('"+saved_userid + "','" + saved_email + "','" + saved_nickname+ "')");

                }
            });
        }

        @JavascriptInterface
        public void updateUserInfo(final String userid,final String arg1,final String arg2,final String arg3) {

            Log.d(TAG,"인스톨시간"+Long.toString(install_date));

            SharedPreferences.Editor editor = prefs.edit();
             if(userid !=null)
            editor.putString("userid", userid);
            editor.putString("arg1", arg1);
            editor.putString("arg2", arg2);
            editor.putString("arg3", arg3);
            editor.commit();
            Log.d(TAG,userid+"saved");
            //  }

        }

        @JavascriptInterface
        public void getSharedPreferences() {
            Log.d(TAG,"프리퍼런스 호출"+Long.toString(install_date));

            //저장되어 있는 프리퍼런스의 값을 보내준다.
            SharedPreferences.Editor editor = prefs.edit();
            final String saved_userid = prefs.getString("userid", "");
            final String saved_arg1 = prefs.getString("arg1", "");
            final String saved_arg2 = prefs.getString("arg2", "");
            final String saved_arg3 = prefs.getString("arg2", "");

            webView.post(new Runnable() {
                @Override
                public void run() {
                    Log.d(TAG,saved_userid+" called");
                    // webView.loadUrl("javascript:app.set_device_base_info('" + phone + "','" + Android_id + "','" + token + "')");
                    webView.loadUrl("javascript:callbackGetSharedPreferences('" + saved_userid + "','" + saved_arg1 + "','" + saved_arg2+ "','" + saved_arg3+ "')");
                }
            });
        }




        @JavascriptInterface
        public void target_main(String string_check) {
            webView.loadUrl(string_check);
            Log.d(TAG, string_check + " url called");
        }

        @JavascriptInterface
        public void action_view(String string_check) {
            Uri uri = Uri.parse(string_check);
            Intent it = new Intent(Intent.ACTION_VIEW, uri);
            mContext.startActivity(it);
            Log.d(TAG, string_check + " url called");
        }

        @JavascriptInterface
        public void load_webviewurl(String string_check) {
            Uri uri = Uri.parse(string_check);
            webView.loadUrl(string_check);
            Log.d(TAG, string_check + " url called");
        }


        @JavascriptInterface
        public void select_tag_excute(String string_check) {
            Log.d(TAG, string_check + " 0string_check called");


            if (string_check.equalsIgnoreCase("stopProgressbar") == true) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        mProgressHorizontal.setVisibility(View.GONE);
                    }
                });
            }
            if (string_check.equalsIgnoreCase("startProgressbar") == true) {
                webView.post(new Runnable() {
                    @Override
                    public void run() {
                        mProgressHorizontal.setVisibility(View.VISIBLE);
                    }
                });

            }


            if (string_check.equalsIgnoreCase("excute_setting_activity") == true) {
                Intent intent = new Intent(mContext, SettingActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }  if (string_check.equalsIgnoreCase("Received_listviewActivity") == true) {
                Intent intent = new Intent(mContext, Received_listviewActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                mContext.startActivity(intent);
            }else if (string_check.equalsIgnoreCase("clear_history") == true) {
                Log.d(TAG, string_check + " string_check called");
                IsClear = true;
            }else if (string_check.equalsIgnoreCase("CloseApp") == true) {
                MainActivity.activity.finish();
            }

        }


        @JavascriptInterface
        public void excute_picture_activity(String string_check) {

            webView.post(new Runnable() {
                @Override
                public void run() {
                    webView.loadUrl("javascript:check_value(this)");
                }
            });

        }


    }



//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        boolean isback = webView.canGoBack();
//
//
//        //webView.goBack();
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//            if (isPageOpen) {
//                // 팝업이 열려있으면 먼저 팝업을 닫음
//                isPageOpen = false;
//                popWindow.startAnimation(translateRightAnim);
//                return true;
//            } else if (webView != null && webView.canGoBack()) {
//                webView.goBack();
//                return true;
//            } else {
//                if (doubleBackToExitPressedOnce) {
//                    backButtonHandler.removeCallbacks(backButtonRunnable);
//                    finish();
//                    return true;
//                }
//
//                doubleBackToExitPressedOnce = true;
//                Toast.makeText(this, "한 번 더 누르면 종료됩니다", Toast.LENGTH_SHORT).show();
//                backButtonHandler.postDelayed(backButtonRunnable, 2000);
//                return true;
//            }
//        }
//        return super.onKeyDown(keyCode, event);
//    }


//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//
//        if (keyCode == KeyEvent.KEYCODE_BACK) {
//
//            if (webView != null) {
//
//
//                if(newWebView!=null && newWebView.canGoBack()) {
//                    newWebView.goBack();
//                    return false;
//                }else if(newWebView!=null && newWebView.canGoBack()==false){
//                    isPageOpen = false;
//                    popWindow.startAnimation(translateRightAnim);
//
//                    return false;
//                }
//
//                // if (webView.canGoBack() && !screen_home_postion) {
//                if (webView.canGoBack()) {
//                    webView.goBack();
//
//                    return false;
//                } else {
//
//
//                    String alertTitle = getResources().getString(R.string.app_name);
//                    String buttonMessage = getResources().getString(
//                            R.string.alert_msg_exit);
//                    String buttonYes = getResources()
//                            .getString(R.string.button_yes);
//                    String buttonNo = getResources().getString(R.string.button_no);
//
//                    AlertDialog A  = new AlertDialog.Builder(MainActivity.this)
//                            .setIcon(R.mipmap.ic_launcher)
//                            .setTitle(alertTitle)
//                            .setMessage(buttonMessage)
//                            .setPositiveButton(buttonYes,
//                                    new DialogInterface.OnClickListener() {
//
//                                        @Override
//                                        public void onClick(DialogInterface dialog,
//                                                            int which) {
//                                            // TODO Auto-generated method stub
//                                            // moveTaskToBack(true);
//
//                                            webView.post(new Runnable() {
//                                                @Override
//                                                public void run() {
//                                                    ///  Toast.makeText(MainActivity.this,"로그아웃 중입니다", Toast.LENGTH_LONG).show();
//                                                    webView.loadUrl("javascript:app.logout()");
//                                                }
//                                            });
//
//
//                                            Timer timer = new Timer();
//                                            timer.schedule( new TimerTask()
//                                                            {
//                                                                public void run()
//                                                                {
//                                                                    moveTaskToBack(true);
//                                                                    finish();
//                                                                    Process.killProcess(Process.myPid());
//                                                                }
//                                                            }
//                                                    , 500);
//
//
//
//
//
//                                        }
//                                    }).setNegativeButton(buttonNo, null).show();
//
//                    A.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
//                    A.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
//
//                }
//            }
//        }
//
//
//
//        return super.onKeyDown(keyCode, event);
//    }


    private  void check_app_version() {

        int registeredVersion = prefs.getInt(PROPERTY_APP_VERSION, 0);
        currentVersion = getAppVersion(context);
      //  SharedPreferences.Editor editor = prefs.edit();
        Log.d(TAG, "registeredVersion=" + registeredVersion + " currentVersion=" + currentVersion + " App version.");

   ///     if(token_refreshed) {
//            editor.putBoolean("token_refreshed",false);// 앱이 재시작 할때 토큰을 저장하게 시킨다
//            editor.commit();
//            regist task1 = new regist();
//            task1.execute(getResources().getString(R.string.Server_regid_url), token, Str_MyPhoneNumber, "");
  ///      }


        if (registeredVersion == 0) {
            editor.putInt(PROPERTY_APP_VERSION, currentVersion);
            editor.putInt("IntPopupCount", 1);
            editor.commit();

        } else {

            Intpopupcount = prefs.getInt("IntPopupCount", 1);
            if (Intpopupcount < 17) {
                Intpopupcount = Intpopupcount + 1;
                editor.putInt("IntPopupCount", Intpopupcount);
                editor.commit();
            }

            if (registeredVersion != currentVersion) {
                Log.d(TAG, "App version changed.");
                registration_ready = false;
                editor.putBoolean("registration_ready", registration_ready);
                editor.putInt(PROPERTY_APP_VERSION, currentVersion);
                editor.commit();
             //   go_MainActivity_other(context);
                Toast.makeText(context,"새로운 버전으로 업데이트 되었습니다!", Toast.LENGTH_LONG).show();


            }
        }
    }

    public static int getAppVersion(Context context) {
        try {
            PackageInfo packageInfo = context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            currentVersionName = packageInfo.versionName;
            return packageInfo.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            throw new RuntimeException("Could not get package name: " + e);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        int[] location = new int[2];
        // Get the x, y location and store it in the location[] array
        // location[0] = x, location[1] = y.
        location[0] = 124;
        location[1] = 410;
        //Initialize the Point with x, and y positions
        p = new Point();
        p.x = location[0];
        p.y = location[1];

        if(hasFocus) {
            checkGPSService();

        }
    }

    @SuppressLint("MissingPermission")
    public boolean checkGPSService() {

        LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        if(!manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            // GPS OFF 일때 Dialog 표시
          new MaterialDialog.Builder(this).title("위치 서비스 설정").content("위치 서비스 기능(GPS)을 설정해주세요.").positiveText("확인").onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    // GPS설정 화면으로 이동
                    Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    startActivity(intent);
                }
            }).buttonRippleColor(getResources().getColor(android.R.color.black)).backgroundColor(getResources().getColor(android.R.color.white)).cancelable(false).canceledOnTouchOutside(false).show();

            return false;
        } else {
            return true;
        }
    }

    public static boolean isGpsEnabled(Context context) {

            final int locationMode;
            try {
                locationMode = Settings.Secure.getInt(context.getContentResolver(),
                        Settings.Secure.LOCATION_MODE);
            } catch (Settings.SettingNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            switch (locationMode) {

                case Settings.Secure.LOCATION_MODE_HIGH_ACCURACY:
                case Settings.Secure.LOCATION_MODE_SENSORS_ONLY:
                    return true;
                case Settings.Secure.LOCATION_MODE_BATTERY_SAVING:
                case Settings.Secure.LOCATION_MODE_OFF:
                default:
                    return false;
            }

    }

    class CntTimer extends CountDownTimer {

        public CntTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
            isTwoClickBack = true;
        }

        @Override
        public void onFinish() {// 타이머가 완료된후 실행된다.
            // TODO Auto-generated method stub
            isTwoClickBack = false;
            webView.stopLoading();
            webView = null;
        }

        @Override
        public void onTick(long millisUntilFinished) {
            // TODO Auto-generated method stub
            Log.i("Test", " isTwoClickBack " + isTwoClickBack);
        }
    }


    private static boolean isPackageInstalled(String packageName, PackageManager packageManager) {
        try {
            packageManager.getPackageInfo(packageName, 0);
            return true;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }


    private  boolean callProgram(final String url, final Context mContext , String package_name){
        //크롬브라우저 패키지명
        //    String packageName = "com.android.chrome";
        String  packageName = package_name;
        final Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setPackage(packageName); //바로 이 부분
        i.setData(Uri.parse(url));


        // 앱설치 체크를 합니다.

        if(!isPackageInstalled(i.getPackage(), context.getPackageManager())) {
            String packagename = i.getPackage();

            if ( packagename != null )
            {
                try{
                    startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse( "market://search?q=pname:" + packagename ) ) );
                    return true;
                }catch (ActivityNotFoundException e) {

                    // startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName)));
                    // callProgram(url,getApplicationContext(),"com.ddd.gachita");
                    return    url_scheme_intent( webView, url );
                }



            }

        }





                /*
                if ( getActivity().getPackageManager().resolveActivity( intent, 0 ) == null )
                {
                    String packagename = intent.getPackage();

                    if ( packagename != null )
                    {
                        startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse( "market://search?q=pname:" + packagename ) ) );

                        return true;
                    }
                }
                */
        Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( i.getDataString() ) );

        try{
            startActivity( intent );
        }catch( ActivityNotFoundException e ) {
            Log.d( SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]" );
            return false;
        }




//            Intent go_intent = new Intent();
//            go_intent.setAction(Intent.ACTION_VIEW);
//            go_intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//            go_intent.setData( Uri.parse( url ) );
//            mContext.startActivity(go_intent);
            return  false;
        }




    public static void callChrome(String url, Context mContext){
        String packageName = "com.android.chrome";
        // String packageName = "vitamina.mobile";

        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setPackage(packageName); //바로 이 부분
        i.setData(Uri.parse(url));

        //크롬브라우저가 설치되어있으면 호출, 없으면 마켓으로 설치유도
        //크롬브라우저가 설치되어있으면 호출, 없으면 마켓으로 설치유도
        if (Build.VERSION.SDK_INT >= 30) {
            // 앱설치 체크를 합니다.

            if(!isPackageInstalled(i.getPackage(), mContext.getPackageManager())) {
                String packagename = i.getPackage();

                if ( packagename != null )
                {
                    try{
                        mContext.startActivity( new Intent( Intent.ACTION_VIEW, Uri.parse( "market://search?q=pname:" + packagename ) ) );

                    }catch (ActivityNotFoundException e) {

                        // startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(GOOGLE_PLAY_STORE_PREFIX + packageName)));
                        // callProgram(url,getApplicationContext(),"com.ddd.gachita");
                    }
                }

            }

            Intent intent = new Intent( Intent.ACTION_VIEW, Uri.parse( i.getDataString() ) );
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            try{
                mContext.startActivity( intent );
            }catch( ActivityNotFoundException e ) {
                Log.d( SampleApplication.m_strLogTag, "[PayDemoActivity] ActivityNotFoundException=[" + e.getMessage() + "]" );

            }

        }else{
            List<ResolveInfo> activitiesList = mContext.getPackageManager().queryIntentActivities(i, -1);
            // Toast.makeText(mContext, "발견수"+activitiesList.size(), Toast.LENGTH_SHORT).show();
            Log.d("bb",activitiesList.size()+"ok1");
            if(activitiesList.size() == 0) {

                Toast.makeText(mContext, "먼저 크롬 브라우저 설치로 이동합니다. 설치후 이용해 주세요", Toast.LENGTH_LONG).show();


                Intent go_intent2 = new Intent();
                go_intent2.setAction(Intent.ACTION_VIEW);
                go_intent2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                go_intent2.setData( Uri.parse("market://details?id=" + packageName) ) ;
                mContext.startActivity(go_intent2);


            } else {
                // Intent go_intent = new Intent();
                i.setAction(Intent.ACTION_VIEW);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                i.setData( Uri.parse( url ) );
                mContext.startActivity(i);
            }
        }


    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent.getExtras() != null) {
            Log.d(TAG,"pass2886");
            p_messsage = intent.getExtras().getString("message");
            subject = intent.getExtras().getString("title");
            weblink = intent.getExtras().getString("url");
            imgUrl = intent.getExtras().getString("file_url");
            arg1 = intent.getExtras().getString("arg1");
            Log.d(TAG, "message=" + p_messsage);
            Log.d(TAG, "subject=" + subject);
            Log.d(TAG, "weblink=" + weblink);
            Log.d(TAG, "imgUrl=" + imgUrl);
            Log.d(TAG, "arg1=" + arg1);


        }

        if(TextUtils.isEmpty(subject)) subject = getResources().getString(R.string.app_name);
        if (imgUrl != null) new RetriveTweetTask().execute(imgUrl);
        try {
            p_messsage = p_messsage.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
            p_messsage = p_messsage.replaceAll("\\+", "%2B");

            p_messsage = URLDecoder.decode(p_messsage, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Log.d(TAG,"imgUrl==>"+ imgUrl);
    }

//    @Override
//    protected void onNewIntent(Intent intent) {
//        super.onNewIntent(intent);
//        try {
//            if (intent.getExtras() != null) {
//                Log.d(TAG,"pass2886");
//                p_messsage = intent.getExtras().getString("message", "");
//                subject = intent.getExtras().getString("title", "");
//                weblink = intent.getExtras().getString("url", "");
//                imgUrl = intent.getExtras().getString("file_url", "");
//                arg1 = intent.getExtras().getString("arg1", "");
//                Log.d(TAG, "message=" + p_messsage);
//                Log.d(TAG, "subject=" + subject);
//                Log.d(TAG, "weblink=" + weblink);
//                Log.d(TAG, "imgUrl=" + imgUrl);
//                Log.d(TAG, "arg1=" + arg1);
//
//                // 메시지 처리 플래그 설정
//                message_found = true;
//
//                // 알림 처리 로직
//                if (p_messsage != null && !p_messsage.isEmpty()) {
//                    try {
//                        // 특수 문자 처리
//                        p_messsage = p_messsage.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
//                        p_messsage = p_messsage.replaceAll("\\+", "%2B");
//                        p_messsage = URLDecoder.decode(p_messsage, "UTF-8");
//                    } catch (Exception e) {
//                        Log.e(TAG, "메시지 디코딩 오류: " + e.getMessage());
//                    }
//
//                    // 이미지가 있는 경우 이미지 로드 후 다이얼로그 표시
//                    if (imgUrl != null && !imgUrl.isEmpty()) {
//                        new RetriveTweetTask().execute();
//                    } else {
//                        // 이미지가 없는 경우 바로 다이얼로그 표시
//                        MyPushCustomAlertDialog();
//                    }
//                } else if (weblink != null && !weblink.isEmpty()) {
//                    // 메시지가 없고 웹링크만 있는 경우 직접 웹링크로 이동
//                    loadUrlWithHistory(weblink);
//                }
//            }
//        } catch (Exception e) {
//            Log.e(TAG, "onNewIntent 오류: " + e.getMessage());
//            e.printStackTrace();
//            // 기본 동작으로 다이얼로그 표시 시도
//            try {
//                if (p_messsage != null && !p_messsage.isEmpty()) {
//                    MyPushCustomAlertDialog();
//                } else if (weblink != null && !weblink.isEmpty()) {
//                    loadUrlWithHistory(weblink);
//                }
//            } catch (Exception ex) {
//                Log.e(TAG, "다이얼로그 표시 오류: " + ex.getMessage());
//            }
//        }
//    }


    public static boolean isAppRunning(Context context){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> procInfos = activityManager.getRunningAppProcesses();
        for(int i = 0; i < procInfos.size(); i++){
            if(procInfos.get(i).processName.equals(context.getPackageName())){
                return true;
            }
        }

        return false;
    }


    public class CustomRelativeLayout extends RelativeLayout {

        private WebView mWebView;
        private Button mButton;
        ProgressBar mProgressHorizontalPopup;

        public CustomRelativeLayout(Context context) {
            super(context);
            mWebView = new WebView(context);
            // mWebView.setId(0X100);
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
            mWebView.generateViewId();
            else mWebView.setId(R.id.nwebviewId);
            mWebView.setScrollContainer(false);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            mWebView.setLayoutParams(params);
            mWebView.setBackgroundColor(Color.WHITE);
            mButton = new Button(context);
            //else mButton.setId(0X101);
            //
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN)
            mButton.generateViewId();
            else mButton.setId(R.id.svId);
            mButton.setText("X");

            mProgressHorizontalPopup = new ProgressBar(context);
            RelativeLayout.LayoutParams params2 = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

            params2.addRule(RelativeLayout.CENTER_IN_PARENT);
            params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
            mProgressHorizontalPopup.setLayoutParams(params2);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //  mProgressHorizontalPopup.setIndeterminateTintList(ColorStateList.valueOf(R.color.pg1));
                mProgressHorizontalPopup.setBackgroundTintList(ColorStateList.valueOf(Color.RED));
            }

            //  mButton.setBackgroundColor(Color.TRANSPARENT);
            RelativeLayout.LayoutParams bparams = new RelativeLayout.LayoutParams(
                    RelativeLayout.LayoutParams.WRAP_CONTENT,
                    RelativeLayout.LayoutParams.WRAP_CONTENT);
            bparams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
            bparams.addRule(RelativeLayout.ALIGN_TOP, mWebView.getId());
            mButton.setLayoutParams(bparams);
            addView(mWebView);
            // addView(mButton);
            addView(mProgressHorizontalPopup);
            mButton.setVisibility(View.GONE);
            mProgressHorizontalPopup.setVisibility(View.GONE);
            mButton.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //  Toast.makeText(v.getContext(),"Dynamic button is clicked", 3000).show();

                }
            });


        }
        public ProgressBar getTheProgrss() {
            return mProgressHorizontalPopup;
        }


        public WebView getTheWebView() {
            return mWebView;
        }

        public Button getTheButton() {
            return mButton;
        }

        /* public RelativeLayout getRL() {
            return bparams;
        }*/

    }

    private class SlidingPageAnimatinListener implements Animation.AnimationListener{

        @Override
        public void onAnimationEnd(Animation animation) {
            // TODO Auto-generated method stub
            if(isPageOpen)isPageOpen=true;
            else
            {
                isPageOpen=false;
                mContainer.removeView(popWindow);
                newWebView.destroy();
                newWebView = null;

                popWindow.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            }

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onAnimationStart(Animation animation) {
            // TODO Auto-generated method stub


        }

    }


    private void restartApp() {

        Intent intent = new Intent(this, splash.class);
        this.startActivity(intent);
      //  this.finishAffinity();
    }




    private BroadcastReceiver completeReceiver = new BroadcastReceiver() {

        @Override

        public void onReceive(Context context, Intent intent) {

            Resources res = context.getResources();
            Toast toast = Toast.makeText(MainActivity.this,
                    getResources().getString(R.string.download_finish), Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER_HORIZONTAL
                    | Gravity.CENTER_VERTICAL, 0, 0);
            toast.show();
            // 다운로드 완료 창으로 이동
            startActivity(new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS));

        }

    };
    public void go_img_url(View v){
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(imgUrl));
        startActivity(intent);
    }

    // AsyncTask<Params,Progress,Result>
    public class RetriveTweetTask extends AsyncTask<String, Void, HttpResponse> {

        @Override
        protected HttpResponse doInBackground(String... urls) {
            try {
                if (imgUrl == null || imgUrl.isEmpty()) {
                    Log.e(TAG, "이미지 URL이 비어있습니다");
                    return null;
                }
                
                url = new URL(imgUrl);
                URLConnection conn = url.openConnection();
                conn.setConnectTimeout(10000); // 10초 타임아웃 설정
                conn.setReadTimeout(15000);    // 15초 타임아웃 설정
                conn.connect();
                
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                imgBitmap = BitmapFactory.decodeStream(bis);
                bis.close();
                
                if (imgBitmap == null) {
                    Log.e(TAG, "이미지를 로드할 수 없습니다: " + imgUrl);
                }
                
                Log.d(TAG, "알림 이미지 로드 성공");
            } catch (MalformedURLException e) {
                Log.e(TAG, "잘못된 URL 형식: " + e.getMessage());
                e.printStackTrace();
            } catch (IOException e) {
                Log.e(TAG, "이미지 로드 오류: " + e.getMessage());
                e.printStackTrace();
            } catch (Exception e) {
                Log.e(TAG, "알 수 없는 오류: " + e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(HttpResponse result) {
            super.onPostExecute(result);
            try {
                if (imgBitmap != null && img != null) {
                    img.setImageBitmap(imgBitmap);
                    img.setVisibility(View.VISIBLE);
                } else if (img != null) {
                    img.setVisibility(View.GONE);
                }
                
                // 이미지 로딩 완료 후 다이얼로그 표시 (웹링크가 있고 MyPushCustomAlertDialog에서 직접 처리하도록 함)
                if (p_messsage != null && !p_messsage.isEmpty()) {
                    MyPushCustomAlertDialog();
                } else if (weblink != null && !weblink.isEmpty()) {
                    // 메시지가 없고 웹링크만 있는 경우 직접 로드
                    loadUrlWithHistory(weblink);
                }
            } catch (Exception e) {
                Log.e(TAG, "이미지 표시 오류: " + e.getMessage());
                e.printStackTrace();
                
                // 오류 발생해도 웹링크가 있으면 로드 시도
                if (weblink != null && !weblink.isEmpty()) {
                    loadUrlWithHistory(weblink);
                }
            }
        }
    }

    private class LocationControl extends AsyncTask<Context, Void, Void>
    {
        private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

        protected void onPreExecute()
        {
            this.dialog.setMessage("위치정보를 가져오고 있습니다.");
         //   this.dialog.show();
        }

        protected Void doInBackground(Context... params)
        {
            //Wait 10 seconds to see if we can get a location from either network or GPS, otherwise stop
            Long t = Calendar.getInstance().getTimeInMillis();
            while (!hasLocation && Calendar.getInstance().getTimeInMillis() - t < 15000) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            };
            return null;
        }

        protected void onPostExecute(final Void unused)
        {
            if(this.dialog.isShowing())
            {
            ///    webView.loadUrl("javascript:set_value_location('" + now_lati + "','" + now_longi + "')");
                this.dialog.dismiss();
                hasLocation = false;
            }
        }
    }

    // webView의 URL을 로드하되 히스토리가 유지되도록 하는 메서드
    public static void loadUrlWithHistory(String url) {
        if (webView == null) return;
        
        if (url == null || url.isEmpty()) {
            Log.e(TAG, "URL이 비어있습니다");
            return;
        }
        
        // 기본 URL 구조 확인
        if (!url.startsWith("http://") && !url.startsWith("https://")) {
            // http 또는 https로 시작하지 않으면 https:// 추가
            url = "https://" + url;
        }
        
        final String finalUrl = url;
        Log.d(TAG, "웹뷰 URL 로드: " + finalUrl);
        
        webView.post(new Runnable() {
            @Override
            public void run() {
                try {
                    String currentUrl = webView.getUrl();
                    
                    // 현재 URL이 없거나 로드할 URL과 다른 경우에만 새로 로드
                    if (currentUrl == null || !currentUrl.equals(finalUrl)) {
                        // URL 히스토리에 추가
                        urlHistory.push(finalUrl);
                        Log.d(TAG, "URL 히스토리에 추가: " + finalUrl + ", 크기: " + urlHistory.size());
                        
                        // 웹뷰 로드 (웹뷰가 자체적으로 히스토리 유지)
                        webView.loadUrl(finalUrl);
                    } else {
                        Log.d(TAG, "현재 URL과 동일하여 로드하지 않음: " + finalUrl);
                    }
                } catch (Exception e) {
                    Log.e(TAG, "URL 로드 오류: " + e.getMessage());
                    // 오류 시 로드 시도
                    webView.loadUrl(finalUrl);
                }
            }
        });
    }

    /**
     * 현재 URL에서 파라미터를 제외한 기본 주소만 반환하는 메서드
     * @return 파라미터가 제거된 기본 URL 반환
     */
    public static String getCurrentBaseUrl() {
        if (webView == null) return "";
        
        String currentUrl = webView.getUrl();
        if (currentUrl == null || currentUrl.isEmpty()) return "";
        
        // 쿼리 파라미터 제거 (? 기호 이후 부분 제거)
        int queryIndex = currentUrl.indexOf('?');
        if (queryIndex > 0) {
            currentUrl = currentUrl.substring(0, queryIndex);
        }
        
        // 앵커(#) 제거
        int anchorIndex = currentUrl.indexOf('#');
        if (anchorIndex > 0) {
            currentUrl = currentUrl.substring(0, anchorIndex);
        }
        
        // 마지막 슬래시(/) 처리 (선택적)
        if (currentUrl.endsWith("/")) {
            return currentUrl; // 슬래시 유지
        } else {
            return currentUrl; // 또는 필요에 따라 return currentUrl + "/";
        }
    }
}
