在单击链接之前,Android Webview不会加载会话

时间:2016-08-12 13:04:27

标签: javascript android session cookies webview

我的应用中的webview在点击链接之前不会加载以前使用该应用的会话,而且我还可以执行许多js命令,但在点击链接之前无法重定向。< / p>

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Paper.init(this);
    myApp = getApplicationContext();
    final Intent intent = getIntent();
    URLloja = getString(R.string.loja_address);
    file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/Android/data/"+getPackageName()+"/Produtos/produto.png");

    //Relaciona todos os elementos da activity a variaveis.
    mWebView = (AdvancedWebView) findViewById(R.id.activity_main_webview);
    mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
    mActionBar = getSupportActionBar();
    mWebSettings = mWebView.getSettings();
    mWifiOFF = (ImageView) findViewById(R.id.imageView1);
    mNavigationView = (NavigationView) findViewById(R.id.nav_view);
    mNavigationMenu = mNavigationView.getMenu();
    mProgressBar = (ImageView) findViewById(R.id.progressBar1);
    mWifiOFF.setVisibility(View.INVISIBLE);
    mProgressBar.setVisibility(View.INVISIBLE);
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.activity_main_swipe_refresh_layout);

    mWebView.setCookiesEnabled(true);
    mWebView.setThirdPartyCookiesEnabled(true);
    mWebSettings.setJavaScriptEnabled(true);
    mWebSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    mWebSettings.setDomStorageEnabled(true);
    mWebSettings.setAllowContentAccess(true);

    //Configura sidebar
    //addDrawerItems(); //Heavy
    int menuSize = intent.getIntExtra("Tamanho",0);
    listaItens = new String[2][menuSize];
    listaItens[0] = intent.getStringArrayExtra("Menu");
    listaItens[1] = intent.getStringArrayExtra("Link");

    mActionBar.setDisplayHomeAsUpEnabled(true);
    mActionBar.setHomeAsUpIndicator(R.drawable.ic_menu_white_24dp);
    mActionBar.setHomeButtonEnabled(true);
    mActionBar.setElevation(0);
    setupDrawer(); //Semi-Heavy
    mActionBar.openOptionsMenu();
    setupCountDrawer();

    //Pega o link para o botão compartilhar
    new getShareImage().execute(mWebView.getUrl());

    mWebView.setWebViewClient(new WebViewClient(){
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if(!isConnectedToWiFiOrMobileNetwork(myApp)){
                mWebView.setVisibility(View.INVISIBLE);
                mWifiOFF.setVisibility(View.VISIBLE);
                internetDialog();
            }

            if(Uri.parse(url).getHost().endsWith(URLloja)
                    || Uri.parse(url).getHost().endsWith("montarumalojavirtual.com.br")
                    ){
                return false;
            }

            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
            view.getContext().startActivity(intent);

            return true;
        }
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon){
            String st = cookies.getCookie("http://"+URLloja+"/");
            Paper.book().write("Cookies",st);
            new getShareImage().execute(url);
            reloaded = false;
            mWebView.animate().translationY(2000).setInterpolator(new FastOutSlowInInterpolator()).setDuration(300).setListener(new Animator.AnimatorListener() {
                @Override public void onAnimationStart(Animator animator) {}
                @Override public void onAnimationCancel(Animator animator) { }
                @Override public void onAnimationRepeat(Animator animator) { }
                @Override public void onAnimationEnd(Animator animator) {
                    mWebView.setVisibility(View.GONE);
                }
            });
            mProgressBar.setVisibility(View.VISIBLE);
            Animation anim = AnimationUtils.loadAnimation(myApp, R.anim.blinking);
            mProgressBar.startAnimation(anim);
            carregaCSS();
        }
        @Override
        public void onPageFinished(WebView view, final String url){

            carregaCSS();
            getCounters();
            super.onPageFinished(view, url);
            mWebView.loadUrl("javascript: " + "function ajusteCarrinho(){"  +
                    " $('td.image').each(function(){" +
                    " $(this).append($(this).next());" +
                    " jaAjustado = true; " +
                    "});" +
                    "}" +
                    "ajusteCarrinho();" +
                    "");
        }
        @Override
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl){
            //Tratar erros de carregamento aqui
            mWebView.setVisibility(View.INVISIBLE);
            mWifiOFF.setVisibility(View.VISIBLE);
        }

    });

    mWebView.setWebChromeClient(new WebChromeClient() {
        @Override
        public void onReceivedTitle(WebView view,String sTitle){
            super.onReceivedTitle(view, sTitle);
            if(sTitle!=null && sTitle.length()>0){
                mActionBar.setTitle(sTitle);
            } else{
                mActionBar.setTitle(R.string.title_activity_web_view);
            }
        }
        public void onCloseWindow(WebView w){
            super.onCloseWindow(w);
            finish();
        }

        public boolean onConsoleMessage(ConsoleMessage cm)
        {
            if(cm.message().contains("ContadorCarrinho"))
            {
                int first = cm.message().indexOf(" ")+1,
                        last =  cm.message().indexOf("item");

                String contador = cm.message().subSequence(first,last).toString().trim();
                mCartCount.setText(contador);
            }
            if(cm.message().contains("ContadorDesejo"))
            {
                int first = cm.message().indexOf("(")+1,
                        last =  cm.message().indexOf(")");

                String contador = cm.message().subSequence(first,last).toString().trim();

                mWishCount.setText(contador);
            }
            if(cm.message().contains("imageShare:url(")){
                String imageShare = cm.message().substring(cm.message().indexOf("\""),
                        cm.message().lastIndexOf("\""));
            }
            Log.d("ShowMote", cm.message() + " -- From line "
                    + cm.lineNumber() + " of "
                    + cm.sourceId() );
            return true;
        }
        public void onProgressChanged(WebView view, int progress)
        {
            carregaCSS();
            if(progress>60 && !reloaded){
                mProgressBar.setVisibility(View.INVISIBLE);
                mProgressBar.clearAnimation();
                mWebView.setTranslationY(0);
                mWebView.setTranslationX(-2000);
                mWebView.setVisibility(View.VISIBLE);
                mWebView.animate().translationX(0).setDuration(200).setListener(null);
                reloaded=true;
            }
        }
    });

    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            mWebView.reload();
            swipeRefreshLayout.setRefreshing(false);
        }
    });

    mWebView.getViewTreeObserver().addOnScrollChangedListener(mOnScrollChangedListener =
            new ViewTreeObserver.OnScrollChangedListener() {
                @Override
                public void onScrollChanged() {
                    if (mWebView.getScrollY() == 0)
                        swipeRefreshLayout.setEnabled(true);
                    else
                        swipeRefreshLayout.setEnabled(false);

                }
            });
    cookies = CookieManager.getInstance();
    cookies.acceptCookie();

    //Abre link externo
    final String action = intent.getAction();
    if (Intent.ACTION_VIEW.equals(action)) {
        final Uri segments = intent.getData();
        externalURL = segments.toString();
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                mWebView.loadUrl(externalURL);
            }
        });
        Log.i("", "msg");
    }
    else{
        mWebView.post(new Runnable() {
            @Override
            public void run() {
//              mWebView.loadUrl("http://"+URLloja+"/");
                mWebView.loadUrl("javascript: function redirect(){window.location = 'http://"+URLloja+"/' ;} redirect();");
            }
        });
    }
}

我正在使用标准Webview开发,然后我切换到Advanced WebView,它扩展了Webview,看看它是否能解决我的问题,但一切都还是一样。

正如您所看到的,代码需要清理,但与webview无关。 而我正在尝试使用onCreate中的一些重要内容。

0 个答案:

没有答案