【问题标题】:why has my WebView behaviour changed when opening URLs?为什么打开 URL 时我的 WebView 行为发生了变化?
【发布时间】:2017-01-01 01:19:24
【问题描述】:

我最近意识到,我的 android 应用程序中显示超链接图像的 webview 在点击时不再调用浏览器(我猜这是默认行为),而是在内部打开 url 内容。我只对 MainActivity.java 做了一些更改,所以我想知道它是否与这些更改有关。我在下面发布了我之前/之后的代码。任何帮助表示赞赏。 之前:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);


    String bannerURL="http://www.dadhesab.ir/appbanner";
    WebView myWebView = (WebView) findViewById(R.id.webview);
    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected() )
    {
        myWebView.loadUrl(bannerURL);
        myWebView.setVisibility(View.VISIBLE);




    }
    else
    {

    }
    TextView copyrightnotice=(TextView) findViewById(R.id.copyrightNotice);
    int year = Calendar.getInstance().get(Calendar.YEAR);
    copyrightnotice.setText(String.format(getString(R.string.copyrightnotice)) + " © " + year );

}

之后:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);



    String bannerURL="http://www.dadhesab.ir/appbanner";
    final WebView myWebView = (WebView) findViewById(R.id.webview);
    final ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = conMgr.getActiveNetworkInfo();
    if (activeNetwork != null && activeNetwork.isConnected() )
    {
        myWebView.loadUrl(bannerURL);
        myWebView.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                myWebView.setVisibility(View.VISIBLE);

            }
        });

        try {
            // Create a URL for the desired page
            URL url = new URL("http://dadhesab.ir/appversion.txt");

            // launch task
            new ReadTextTask().execute(url);
        }
        catch (MalformedURLException e) {
            // ** do something here **
        }


    }
    else
    {

    }
    TextView copyrightnotice=(TextView) findViewById(R.id.copyrightNotice);
    int year = Calendar.getInstance().get(Calendar.YEAR);
    copyrightnotice.setText(String.format(getString(R.string.copyrightnotice)) + " © " + year );

}

private class ReadTextTask extends AsyncTask<URL, Void, String> {
    String latestvc = null;

    @Override
    protected String doInBackground(URL... urls) {

        try {
            // Read all the text returned by the server
            BufferedReader in = new BufferedReader(new InputStreamReader(urls[0].openStream()));
            latestvc = in.readLine();
            in.close();
        }
        catch (IOException e) {
            // ** do something here **

        }
        return latestvc;
    }

    @Override
    protected void onPostExecute(String result) {
        int versionCode = BuildConfig.VERSION_CODE;

        if (latestvc!=null)//to avoid network conflicts or missing file
        {
            if(versionCode < (Integer.parseInt(latestvc)))
            {
                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);

                // set title
                alertDialogBuilder.setTitle("توجه!");

                // set dialog message
                alertDialogBuilder
                        .setMessage("نسخه جدید دادحساب رسید!")
                        .setPositiveButton("بروزرسانی",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, do sth.
                                Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://cafebazaar.ir/app/ir.dadhesab.dadhesab/?l=fa"));
                                startActivity(browserIntent);                            }
                        })
                        .setNegativeButton("لغو",new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,int id) {
                                // if this button is clicked, just close
                                // the dialog box and do nothing
                                dialog.cancel();
                            }
                        });

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
        }


    }
}

【问题讨论】:

    标签: android android-webview


    【解决方案1】:

    查看此帖子:Support for other protocols in Android webview

    你需要重写 shouldOverridUrlLoading 方法:

    webview.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url != null && url.startsWith("http://")) {
                view.getContext().startActivity(
                    new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } else {
                return false;
            }
        }
    });
    

    致谢:sven

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 2016-01-27
      • 1970-01-01
      • 2013-02-10
      • 1970-01-01
      • 2013-05-13
      • 2018-12-24
      • 2016-06-17
      • 1970-01-01
      相关资源
      最近更新 更多