수정된 MainActivity.java > 자료실

자료실

자료실

수정된 MainActivity.java

페이지 정보

profile_image
작성자 최고관리자
댓글 1 조회 158회 작성일 23-03-16 19:15
작성일 23-03-16 19:15

본문

package com.localhost.MyLocalhostApp;


import android.Manifest;

import android.app.AlertDialog;

import android.app.Dialog;

import android.app.DownloadManager;

import android.content.DialogInterface;


import android.content.Context;

import android.content.Intent;

import android.content.pm.ApplicationInfo;

import android.content.pm.PackageInfo;

import android.content.pm.PackageManager;

import android.graphics.Bitmap;

import android.content.res.Configuration;

import android.graphics.PixelFormat;

import android.net.Uri;


import android.os.Environment;

import android.os.Vibrator;

import android.support.v4.app.ActivityCompat;

import android.support.v4.content.ContextCompat;

import android.support.v4.widget.SwipeRefreshLayout;

import android.support.annotation.RequiresApi;


import android.os.Build;

import android.os.Bundle;

import android.os.Handler;


import android.support.v7.app.AppCompatActivity;

import android.util.Log;

import android.view.KeyEvent;

import android.view.MotionEvent;

import android.view.View;

import android.view.WindowManager;

import android.webkit.CookieManager;

import android.webkit.CookieSyncManager;

import android.webkit.DownloadListener;


import android.webkit.JsResult;


import android.webkit.ValueCallback;

import android.webkit.WebResourceError;

import android.webkit.WebResourceRequest;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.widget.LinearLayout;

import android.widget.ProgressBar;

import android.widget.Toast;

import java.net.URLDecoder;

import com.localhost.MyLocalhostApp.R;


import static android.view.WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

import static android.view.WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;


public class MainActivity extends AppCompatActivity {

    private static WebView mWebView;

    private String mCurrentUrl;


    private float m_downX;

    private ProgressBar progressBar;

    private SwipeRefreshLayout mySwipeRefreshLayout;


    private static final int STORAGE_PERMISSION_CODE = 123;

    private final static int FILECHOOSER_RESULTCODE=1;

    private ValueCallback<Uri[]> mUploadMessage;

    int count = 1;


    private final static String MAIN_URL = "http://192.168.219.108";


    // BACK 2번 클릭 시 종료 핸들러. 플래그

    private Handler mHandler = new Handler();

    private boolean mFlag = false;

    //String userAgent = new WebView(getBaseContext()).getSettings().getUserAgentString();


    private final long FINISH_INTERVAL_TIME = 2000;//우선 누르는 이벤트사이의 시간 간격을 위해 FINISH_INTERVAL_TIME을 지정해 줍니다.

    private long backPressedTime = 0;

    //설정된 시간 이내에 연속적으로 뒤로가기가 이벤트가 일어났을때만 종료 되는 것 입니다.

    //설정해 놓은 시간이 지나면 다시 두번 눌러야 종료되는 상태로 초기화 됩니다.

    //backPressedTime을 통해 첫번째 뒤로가기 이벤트가 일어난 시간을 알고 있어야 합니다.


    @Override

    public void onConfigurationChanged(Configuration newConfig) {

        super.onConfigurationChanged(newConfig);

        Log.d("onConfigurationChanged" , "onConfigurationChanged");

        if(newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){//세로 전환시

            Log.d("onConfigurationChanged" , "Configuration.ORIENTATION_PORTRAIT");

        }else if(newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE){ //가로전환시

            Log.d("onConfigurationChanged", "Configuration.ORIENTATION_LANDSCAPE");

        }else{


        }

    }


    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        final WebView mWebView = (WebView) findViewById(R.id.web);


        startActivity(new Intent(this, SplashActivity.class));//스플래시


        WebSettings settings = mWebView.getSettings();

        mWebView.getSettings().setJavaScriptEnabled(true);//자바스크립트 허용

        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);// 여러개의 윈도우를 사용할 수 있도록 설정

        mWebView.getSettings().setSupportMultipleWindows(true);// javascript가 window.open()을 사용할 수 있도록 설정

        mWebView.getSettings().setGeolocationEnabled(true);


        mWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE); // 캐시설정

        //  LOAD_CACHE_ELSE_NETWORK  : 캐시 기간만료 시 네트워크 접속

        //  LOAD_CACHE_ONLY : 캐시만 불러옴 (네트워크 사용 X)

        //  LOAD_DEFAULT : 기본 모드, 캐시 사용, 기간 만료 시 네트워크 사용

        //  LOAD_NO_CACHE : 캐시모드 사용안함

        //  LOAD_NORMAL : 기본모드 캐시 사용 @Deprecated

        //mWebView.getSettings().setAppCacheEnabled( false );


        //mWebView.setInitialScale(100);

        //getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); // EditText누르고 키보드 올라올 때 밑에쪽 UI가릴때

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE); // 키패드가 UI를 무시하고 위를 덮을 때:


        //progressBar = findViewById(R.id.progressBar);

        //getInternetStatus();


        if (Build.VERSION.SDK_INT >= 7) {

            // SDK 2.1 부터 HTML5 LocalStorage를 사용할 수 있다.

            settings.setDomStorageEnabled(true);

        }


        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

            //noinspection deprecation

            //자동로그인 하기위해서 쿠키값 onResume, OnPeuse에도 있음

            CookieSyncManager.createInstance(this);

        }


        /* ............ 파일 다운로드               ................................................ */

        // https://onedaycodeing.tistory.com/71 참조

        mWebView.setDownloadListener(new DownloadListener() {

            @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)

            @Override

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

                try {

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

                    DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);


                    // contentDisposition이녀석은 결정적으로 파일이름 입니다.

                    contentDisposition = URLDecoder.decode(contentDisposition,"UTF-8"); //디코딩


                    //String FileName = contentDisposition.replace("attachment; filename=", ""); //attachment; filename*=UTF-8''뒤에 파일명이있는데 파일명만 추출하기위해 앞에 attachment; filename*=UTF-8''제거

                    //String fileName = FileName; //위에서 디코딩하고 앞에 내용을 자른 최종 파일명


                    String[] fileArray = url.split("/");

                    String fileName = fileArray[fileArray.length - 1];


                    request.setMimeType(mimetype); // 확장자

                    request.addRequestHeader("User-Agent", userAgent);

                    request.setDescription("Downloading File"); // 다운로드 설명 : 노티피케이션에 보이는 디스크립션입니다.

                    request.setAllowedOverMetered(true); // True로 설정되면, 모바일네트워크가 연결되었을 때도 다운로드합니다.

                    request.setAllowedOverRoaming(true); // True로 설정되면, 로밍네트워크가 연결되었을 때도 다운로드합니다.

                    request.setTitle(fileName);// 다운로드 제목 : 노티피케이션에 보이는 타이틀입니다.

                    //request.setRequiresCharging(false); // True로 설정되면, 단말이 충전중일 때만 다운로드합니다.

                    request.allowScanningByMediaScanner(); // MediaScanner에서 파일을 검색하는 경우 true입니다. MediaScanner에서 스캔 한 파일은 미디어를 보는 데 사용되는 응용 프로그램 (예 : 갤러리 앱)에 나타납니다.


                    request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);  // 상단바에 완료 결과 놔둠. 0 은 안뜸

                    /*

                        setNotificationVisibility 옵션션

                       VISIBILITY_VISIBLE: 다운로드가 진행중일 때만 노티를 보여주며, 완료되면 보여주지 않습니다.

                        VISIBILITY_VISIBLE_NOTIFY_COMPLETED: 다운로드 진행 중 그리고 완료되었을 때 모두 노티를 보여줍니다.

                        VISIBILITY_VISIBLE_NOTIFY_ONLY_COMPLETION: 다운로드가 완료되었을 때만 노티를 보여줍니다.

                        VISIBILITY_HIDDEN: 노티를 보여주지 않습니다.

                     */


                    request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName); // 공용 다운로드 디렉토리에 저장할 경우 (/storage/emulated/0/Download/)


                    dm.enqueue(request);

                    Toast.makeText(getApplicationContext(),"파일이 다운로드됩니다.", Toast.LENGTH_LONG).show();

                }

                catch (Exception e) {

                    if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

                        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                            Toast.makeText(getBaseContext(), "다운로드를 위해\n권한이 필요합니다.", Toast.LENGTH_LONG).show();

                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1004);

                        }

                        else {

                            Toast.makeText(getBaseContext(), "다운로드를 위해\n권한이 필요합니다.", Toast.LENGTH_LONG).show();

                            ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1004);

                        }

                    }

                }

            }

        });

        /* ............ 파일 다운로드               ................................................ */


        Context context = mWebView.getContext();

        PackageManager packageManager = context.getPackageManager();

        String appName = "APP_CmA_Android"; // 웹뷰로 접속했는지 만든 앱관련 추가

        String appVersion = " (jian; cmaAPPVersion/21.02.16)"; // app명;  년도 월 일

        String appFullName = appName+" "+appVersion; // app명;  년도 월 일

        String userAgent = mWebView.getSettings().getUserAgentString();

        try {

            // App 이름 추출

            ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);

            //appName = packageManager.getApplicationLabel(applicationInfo).toString();// string.xml의 <string name="app_name">어플리게이션명</string>이 agent에 삽입됨


            // App 버전 추출

            PackageInfo packageInfo = packageManager.getPackageInfo(context.getPackageName(), 0);

            //appVersion = String.format("%s", "" + packageInfo.versionName); // 어플리게이션 버전


            // User-Agent에 App 이름과 버전을 붙여서 보내줌

            //userAgent = String.format("%s %s %s", userAgent, appName, appVersion);

            userAgent = String.format("%s %s %s", userAgent, appFullName, "");

            //userAgent += "";


            // 변경된 User-Agent 반영

            //settings.setUserAgentString(userAgent);

            mWebView.getSettings().setUserAgentString(userAgent+"");


        } catch (PackageManager.NameNotFoundException e) {

            // e.printStackTrace();

        }


        mWebView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

        mWebView.getSettings().setUseWideViewPort(true);

        mWebView.getSettings().setLoadWithOverviewMode(true);

        mWebView.setWebViewClient(new mWebViewClient());

        mWebView.setWebChromeClient(new mWebChromeClient());// 크롬  클라이언트 Alert 및 Confirm 적용 시키기


        // loadUrl 메소드 호출하기 전에 cache 를 삭제한다.

        mWebView.clearCache( true );

        mWebView.loadUrl(MAIN_URL);


        //progressbar

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

        progressBar.setVisibility(View.GONE);


        // reload 메소드 호출하기 전에 cache 를 삭제한다.

        mWebView.clearCache( true );

        mWebView.reload( );

    }


    final Context myApp = this;


    // case ERROR_AUTHENTICATION: break;               // 서버에서 사용자 인증 실패

    // case ERROR_BAD_URL: break;                           // 잘못된 URL

    // case ERROR_CONNECT: break;                          // 서버로 연결 실패

    // case ERROR_FAILED_SSL_HANDSHAKE: break;    // SSL handshake 수행 실패

    // case ERROR_FILE: break;                                  // 일반 파일 오류

    // case ERROR_FILE_NOT_FOUND: break;               // 파일을 찾을 수 없습니다

    // case ERROR_HOST_LOOKUP: break;           // 서버 또는 프록시 호스트 이름 조회 실패

    // case ERROR_IO: break;                              // 서버에서 읽거나 서버로 쓰기 실패

    // case ERROR_PROXY_AUTHENTICATION: break;   // 프록시에서 사용자 인증 실패

    // case ERROR_REDIRECT_LOOP: break;               // 너무 많은 리디렉션

    // case ERROR_TIMEOUT: break;                          // 연결 시간 초과

    // case ERROR_TOO_MANY_REQUESTS: break;     // 페이지 로드중 너무 많은 요청 발생

    // case ERROR_UNKNOWN: break;                        // 일반 오류

    // case ERROR_UNSUPPORTED_AUTH_SCHEME: break; // 지원되지 않는 인증 체계

    // case ERROR_UNSUPPORTED_SCHEME: break;          // URI가 지원되지 않는 방식


    /* mWebViewClient extends WebViewClient : s ... */

    private class mWebViewClient extends WebViewClient {

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String overrideUrl) {

            if (overrideUrl.startsWith("tel:")) {

                Intent dial = new Intent(Intent.ACTION_VIEW, Uri.parse(overrideUrl)); // 전화걸기

                startActivity(dial);//현재의 activity 에 대하여 startActivity 호출

                return true;

            } else if (overrideUrl.startsWith("sms:")) {

                Intent dial = new Intent(Intent.ACTION_VIEW, Uri.parse(overrideUrl)); // sms

                startActivity(dial);//현재의 activity 에 대하여 startActivity 호출

                return true;

            }

            if (overrideUrl.startsWith("mailto:")) {

                Intent dial = new Intent(Intent.ACTION_VIEW, Uri.parse(overrideUrl)); // 메일

                startActivity(dial);//현재의 activity 에 대하여 startActivity 호출

                return true;

            }


            // 다른 도메인은 외부 브라우저로

            if(Uri.parse(overrideUrl).getHost().length() == 0) {

                return false;

            }


            //Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(overrideUrl));

            //startActivity(intent);

            view.loadUrl(overrideUrl);

            return true;

        }


        @Override

        public void onPageFinished(WebView view, String url) {

            /* NOTICE 로그인을 한 다음 앱을 종료하고, 다시 앱을 실행했을 때 간헐적으로 로그인이 안 된 상태가 된다.

             이는 웹뷰의 RAM과 영구 저장소 사이에 쿠키가 동기화가 안 되어 있기 때문이다. 따라서 강제로 동기화를 해준다. */

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

                //noinspection deprecation

                CookieSyncManager.getInstance().sync();

            } else {

                // 롤리팝 이상에서는 CookieManager의 flush를 하도록 변경됨.

                CookieManager.getInstance().flush();

            }

        }


    }

    /* mWebViewClient extends WebViewClient : e ... */


    /* mWebChromeClient extends WebChromeClient : s ... */

    // 크롬  클라이언트 Alert 및 Confirm 적용 시키기

    private class mWebChromeClient extends WebChromeClient {


        @Override

        public boolean onCreateWindow(WebView view, boolean dialog, boolean userGesture, android.os.Message resultMsg) {

            view.removeAllViews();

            WebView childView = new WebView(view.getContext());

            childView.getSettings().setJavaScriptEnabled(true);

            childView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);

            childView.getSettings().setSupportMultipleWindows(true);


            childView.setWebChromeClient(this);

            childView.setWebViewClient(new WebViewClient() {

                //@Override

                public void onCloseWindow(WebView window) {

                    window.destroy();

                }

            });


            childView.setLayoutParams(

                new LinearLayout.LayoutParams(

                    WindowManager.LayoutParams.MATCH_PARENT,

                    WindowManager.LayoutParams.MATCH_PARENT

                )

            );

            view.addView(childView);

            WebView.WebViewTransport transport = (WebView.WebViewTransport)resultMsg.obj;

            transport.setWebView(childView);

            resultMsg.sendToTarget();

            return true;

        }


        @Override

        public void onCloseWindow(WebView window) {

            Log.i(getClass().getName(), "onCloseWindow");

            window.setVisibility(View.GONE);

            window.destroy();

            //mWebViewSub=null;

            super.onCloseWindow(window);

        }


        @Override

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

            new AlertDialog.Builder(view.getContext())

                    .setTitle("Alert")

                    .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;

        }


        @Override

        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,

                                         FileChooserParams fileChooserParams) {

            mUploadMessage = filePathCallback;

            requestStoragePermission();


            return true;

        }


        @Override

        public boolean onJsConfirm(WebView view, String overrideUrl, String message, final JsResult result) {

            new AlertDialog.Builder(view.getContext())

                    .setTitle("Confirm")

                    .setMessage(message)

                    .setPositiveButton("Yes",

                            new AlertDialog.OnClickListener(){

                                public void onClick(DialogInterface dialog, int which) {

                                    result.confirm();

                                }

                            })

                    .setNegativeButton("No",

                            new AlertDialog.OnClickListener(){

                                public void onClick(DialogInterface dialog, int which) {

                                    result.cancel();

                                }

                            })

                    .setCancelable(false)

                    .create()

                    .show();

            return true;

        }


    }

    /* mWebChromeClient extends WebChromeClient : e ... */


    /* requestStoragePermission : s ... */

    //Requesting permission

    private void requestStoragePermission() {

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED){

            openFileExplorer();

            return;

        }


        if (ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.READ_EXTERNAL_STORAGE)) {

            //If the user has denied the permission previously your code will come to this block

            //Here you can explain why you need this permission

            //Explain here why you need this permission

        }

        //And finally ask for the permission

        ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);

    }

    /* requestStoragePermission : e ... */


    /* onRequestPermissionsResult : s ... */

    @Override

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        //Checking the request code of our request

        if (requestCode == STORAGE_PERMISSION_CODE) {

            //If permission is granted

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                openFileExplorer();

                //Displaying a toast

//                Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();

            } else {

                //Displaying another toast if permission is not granted

//                Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();

            }

        }

    }

    /* onRequestPermissionsResult : e ... */


    private void openFileExplorer(){

        Intent i = new Intent(Intent.ACTION_GET_CONTENT);

        i.addCategory(Intent.CATEGORY_OPENABLE);

        i.setType("image/*");

        MainActivity.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MainActivity.FILECHOOSER_RESULTCODE );

    }


    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {

        if(requestCode==FILECHOOSER_RESULTCODE)

        {

            if (null == mUploadMessage) return;

            Uri result = intent == null || resultCode != RESULT_OK ? null

                    : intent.getData();

            if(result ==null){

                mUploadMessage.onReceiveValue(null);

            }else{

                mUploadMessage.onReceiveValue(new Uri[]{result});

            }

            mUploadMessage = null;

        }

    }


    public void requestCameraPermission() {

        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[] { android.Manifest.permission.CAMERA, android.Manifest.permission.WRITE_EXTERNAL_STORAGE }, 0);

        }

    }


    // 백버튼 터치시 웹뷰페이지 뒤로 가기. 더이상 뒤로 갈곳이 없으면 연속 두번 터치시 종료

    @Override

    public void onBackPressed() {   // 뒤로가기 누르면 다이얼로그 생성

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setIcon(R.mipmap.ic_launcher); // 다이얼로그 아이콘

        builder.setTitle("종료여부"); // 다이얼로그 제목

        builder.setMessage("정말 종료 하시겠습니까?"); // 다이얼로그 본문 내용

        builder.setCancelable(false);   // 다이얼로그 화면 밖 터치 방지


        builder.setPositiveButton("예", new AlertDialog.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {

                exit();

            }

        });


        builder.setNegativeButton("아니오", new AlertDialog.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {


            }

        });


        builder.setNeutralButton("취소", new AlertDialog.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {


            }

        });

        builder.show(); // 다이얼로그 보이기

    }


    public void ori_onBackPressed() {

        long curTime = System.currentTimeMillis();

        long intervalTime = curTime - backPressedTime;


        //if(mWebView.canGoBack()){

        //	mWebView.goBack(); // 원래소스 아래로 변경함

        if (0 <= intervalTime && FINISH_INTERVAL_TIME >= intervalTime) {

            super.onBackPressed();

        } else {

            backPressedTime = curTime;

            Toast.makeText(this,"Press 'Back' button again to exit.", Toast.LENGTH_SHORT).show();

            //Toast.makeText(this,"'뒤로' 버튼을 한 번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();

        }

    }


    public void exit() { // 종료

        super.onBackPressed();

    }


    /* initWebView : s */

    private void initWebView() {

        mWebView.setWebChromeClient(new MyWebChromeClient(this));

        mWebView.setWebViewClient(new WebViewClient() {

            @Override

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

                super.onPageStarted(view, url, favicon);

                progressBar.setVisibility(View.VISIBLE);

                invalidateOptionsMenu();

            }


            @Override

            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                // 다른 도메인은 외부 브라우저로

                if(Uri.parse(url).getHost().length() == 0) {

                    return false;

                }


                //mWebView.clearCache( true );

                mWebView.loadUrl(url);

                return true;

            }


            @Override

            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);

                progressBar.setVisibility(View.GONE);

//                mySwipeRefreshLayout.setRefreshing(false);

                invalidateOptionsMenu();

            }


            @Override

            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {

                super.onReceivedError(view, request, error);

                progressBar.setVisibility(View.GONE);

//                mySwipeRefreshLayout.setRefreshing(false);

                invalidateOptionsMenu();

            }

        });

        mWebView.clearCache(true);

        mWebView.clearHistory();

        mWebView.getSettings().setJavaScriptEnabled(true);


        mWebView.setHorizontalScrollBarEnabled(false);

        mWebView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {


                if (event.getPointerCount() > 1) {

                    //Multi touch detected

                    return true;

                }


                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN: {

                        // save the x

                        m_downX = event.getX();

                    }

                    break;


                    case MotionEvent.ACTION_MOVE:

                    case MotionEvent.ACTION_CANCEL:

                    case MotionEvent.ACTION_UP: {

                        // set x so that it doesn't move

                        event.setLocation(m_downX, event.getY());

                    }

                    break;

                }


                return false;

            }

        });

    }


    @Override

    protected void onResume() {

        super.onResume();


        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

            //noinspection deprecation

            //자동로그인 하기위해서 쿠키값 onResume, OnPeuse에도 있음

            CookieSyncManager.getInstance().startSync();

        }

    }


    @Override

    protected void onPause() {

        super.onPause();


        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {

            //noinspection deprecation

            //자동로그인 하기위해서 쿠키값 onResume, OnPeuse에도 있음

            CookieSyncManager.getInstance().stopSync();

        }

    }


    private void back() {

        if (mWebView.canGoBack()) {

            mWebView.goBack();

        }

    }


    private void forward() {

        if (mWebView.canGoForward()) {

            mWebView.goForward();

        }

    }


    private class MyWebChromeClient extends WebChromeClient {

        Context context;


        public MyWebChromeClient(Context context) {

            super();

            this.context = context;

        }


        @Override

        public boolean onShowFileChooser(WebView mWebView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {

            mUploadMessage = filePathCallback;

            requestStoragePermission();


            return true;

        }

    }


    // 안드로이드 소프트 키보드 windowSoftInputMode

    /*

    public class PhMainActivity extends AppCompatActivity {

        @Override

        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);

            setContentView(R.layout.activity_main);

            getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);

        }

    }

    */


    /**

     * 웹뷰에 케시가 쌓이는것을 앱이 종료할때마다 비우는 함수

     */

    private void clearApplicationCache(java.io.File dir){

        if(dir==null)

            dir = getCacheDir();

        else;

        if(dir==null)

            return;

        else;

        java.io.File[] children = dir.listFiles();

        try{

            for(int i=0;i<children.length;i++)

                if(children[i].isDirectory())

                    clearApplicationCache(children[i]);

                else children[i].delete();

        }

        catch(Exception e){}

    }


    @Override

    public void onDestroy() {

        super.onDestroy();

        clearApplicationCache(null);

    }


}


추천 2 비추천 0
profile_image

총모아 님의 댓글

총모아 작성일

너무 어려워요!


  • 회사 :
  • 대표 :
  • 주소 :
  • 메일 : admin@mysample.com
  • 사업자 등록번호 :
Copyright © cginjs.com All rights reserved.
notice