mdehghani mdehghani - 3 months ago 13
Android Question

why has my WebView behaviour changed when opening URLs?

I recently realized that the webview in my android app which shows a hyperlinked image doesn't invoke a browser anymore when tapped on (which i guess is the default behaviour), but instead opens the url content internally. I've only made some changes to the MainActivity.java so I was wondering if it might be related to these changes. I've posted my before/after code below. any help is appreciated.
before:

@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 );

}


and after:

@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();
}
}


}
}

Answer

Check this post : Support for other protocols in Android webview

You need to override shouldOverridUrlLoading method :

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;
        }
    }
});

Credits: sven