So I load a page of a website and its show on my android APP via webview.
The website have several images on it; let's say the website page contains 3 images:
<img src="pic_mountain.jpg">
<img src="random_image.php">
<img src="pic_mountain_second.jpg">
my question is, how do I get each of the images above, so I can access each of it as Bitmap on my Java Android apps?
Here is working example to get HTML as string which is loaded in webview and how you can get image url from that after you can convert image url to bitmap.
set webview client to your webview like
webview.setWebViewClient(new WebClientClass());
The webview client is given below
public class WebClientClass extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (progressDialog != null && progressDialog.isShowing())
progressDialog.dismiss();
wvAboutUs.evaluateJavascript(
"(function() { return ('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>'); })();",
new ValueCallback<String>() {
#Override
public void onReceiveValue(String html) {
JsonReader reader = new JsonReader(new StringReader(html));
reader.setLenient(true);
try {
if (reader.peek() != JsonToken.NULL) {
if (reader.peek() == JsonToken.STRING) {
String msg = reader.nextString();
if (msg != null) {
Log.d("HTML", msg);
Pattern p = Pattern.compile("src=\"(.*?)\"");
Matcher m = p.matcher(msg);
if (m.find()) {
Log.d("HTML", m.group(1)); // This will print your image url
}
}
}
}
} catch (IOException e) {
Log.e("TAG", "MainActivity: IOException", e);
} finally {
try {
reader.close();
} catch (IOException e) {
}
}
}
});
}
}
Related
I am developing a cross platform app that has a HybridWebView and displays a local html file. I have a wwwroot folder that contains the html file, css files, js files and all other resources. I have built the complete folder as BundleResource. I also start a local web server with EmbedIO. When I launch the app on iPads(iOS 15>), it does not execute the JavaScript files. On iPhones(iOS 15>) the app works fine. Also on iPads with iOS 12 the app works. Also, the app works on Safari no matter what device is used.
I have already added in info.plist NSAppTransportSecurity with NSAllowsArbitraryLoads = true.Also, I have developed a Swift app with a WebView and tried to use the local web server of the Xamarin.iOS app to present the app there. But again JavaScript is not executed (I also set the preferences regarding JavaScript).
My problem:
I don't understand why the application works on Safari, iPhones and old iPads, but not on new iPads. I suspect that you have to enable JavaScript, but can't find a corresponding solution.
To mention:
I load only one js file in the index.html. This js file in turn loads other js files (This works on all devices except the new iPads, as mentioned above).
Below I have added the HybridWebView.cs, the HybridWebViewRenderer.cs, the MainPage.xaml.cs and MainPage.xaml.
MainPage.xaml:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
xmlns:extensions="clr-namespace:Viewer.Extensions;assembly=Viewer"
x:Class="Viewer.MainPage">
<StackLayout>
<extensions:HybridWebView x:Name="HybridWebView" Uri="{Binding WebViewSource}" VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand" />
</StackLayout>
</ContentPage>
MainPage.xaml.cs:
namespace Viewer
{
[DesignTimeVisible(false)]
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class MainPage : ContentPage
{
private readonly LocalWebServer _server = new LocalWebServer();
private string _webViewSource;
public string WebViewSource
{
get => _webViewSource;
set
{
_webViewSource = value;
OnPropertyChanged(nameof(WebViewSource));
}
}
public MainPage()
{
InitializeComponent();
BindingContext = this;
NavigationPage.SetHasNavigationBar(this, false);
HybridWebView.RegisterAction(data =>
{
DisplayAlert("Alert", "Hello " + data, "OK");
});
HybridWebView.RegisterQRAction(() =>
{
try
{
ZXingScannerPage scanPage = new ZXingScannerPage();
scanPage.OnScanResult += (result) =>
{
scanPage.IsScanning = false;
Device.BeginInvokeOnMainThread(async () =>
{
await Navigation.PopAsync();
var barcode = result.Text.ParseBarcode();
switch (barcode.BarcodeType)
{
case BarcodeType.Hotspot:
{
await HybridWebView.EvaluateJavaScriptAsync(
$"javascript:doLoadHS('{barcode.Datamodule}.html', '{barcode.Hotspot.figureId}', '{barcode.Hotspot.hotspotId}');");
break;
}
case BarcodeType.Datamodule:
default:
{
await HybridWebView.EvaluateJavaScriptAsync(
$"javascript:doLoad('{barcode.Datamodule}.html');");
break;
}
}
});
};
Device.BeginInvokeOnMainThread(() =>
{
Navigation.PushAsync(scanPage);
});
}
catch (Exception ex)
{
DisplayAlert("QR", $"Error while reading qr code: {ex.Message}", "OK");
}
});
HybridWebView.RegisterProjectSelectionAction(() =>
{
_server.Dispose();
Navigation.PopToRootAsync();
});
var docpath = Helper.PathAddBackslash(Path.Combine(DependencyService.Get<IApplicationConfigurationService>().DocumentationRootPath, Init.NAME_DIR_WWWROOT));
_server.StartWebServer(docpath, false, false);
WebViewSource = $"{LocalWebServer.Url}/index.html";
NavigationPage.SetHasBackButton(this, false);
}
protected override bool OnBackButtonPressed()
{
return true;
}
}
}
HybridWebView.cs:
using System;
using Xamarin.Forms;
namespace Viewer.Extensions
{
public class HybridWebView : WebView
{
Action<string> action;
Action qrAction;
Action projectSelectionAction;
public static readonly BindableProperty UriProperty = BindableProperty.Create(
propertyName: "Uri",
returnType: typeof(string),
declaringType: typeof(HybridWebView),
defaultValue: default(string));
public string Uri
{
get { return (string)GetValue(UriProperty); }
set { SetValue(UriProperty, value); }
}
public void RegisterAction(Action<string> callback)
{
action = callback;
}
public void RegisterQRAction(Action callback)
{
qrAction = callback;
}
public void RegisterProjectSelectionAction(Action callback)
{
projectSelectionAction = callback;
}
public void Cleanup()
{
action = null;
qrAction = null;
projectSelectionAction = null;
}
public void InvokeAction(string data)
{
if (action == null || data == null)
{
return;
}
action.Invoke(data);
}
public void InvokeQRAction()
{
qrAction?.Invoke();
}
public void InvokeProjectSelectionAction()
{
projectSelectionAction?.Invoke();
}
}
}
HybridWebViewRenderer.cs:
[assembly: ExportRenderer(typeof(HybridWebView), typeof(HybridWebViewRenderer))]
namespace Viewer.iOS.Views
{
public class HybridWebViewRenderer : WkWebViewRenderer, IWKScriptMessageHandler
{
const string JavaScriptFunction = "function invokeCSharpAction(data){window.webkit.messageHandlers.invokeAction.postMessage(data);}" +
"function invokeCSharpQRAction(data){window.webkit.messageHandlers.invokeQRAction.postMessage(data);}";
WKUserContentController userController;
public HybridWebViewRenderer() : this(new WKWebViewConfiguration())
{
}
public HybridWebViewRenderer(WKWebViewConfiguration config) : base(config)
{
userController = config.UserContentController;
var script = new WKUserScript(new NSString(JavaScriptFunction), WKUserScriptInjectionTime.AtDocumentEnd, false);
userController.AddUserScript(script);
userController.AddScriptMessageHandler(this, "invokeAction");
userController.AddScriptMessageHandler(this, "invokeQRAction");
}
protected override void OnElementChanged(VisualElementChangedEventArgs e)
{
base.OnElementChanged(e);
if (e.OldElement != null)
{
userController.RemoveAllUserScripts();
userController.RemoveScriptMessageHandler("invokeAction");
userController.RemoveScriptMessageHandler("invokeQRAction");
HybridWebView hybridWebView = e.OldElement as HybridWebView;
hybridWebView.Cleanup();
}
if (e.NewElement != null)
{
LoadRequest(new NSUrlRequest(new NSUrl(((HybridWebView)Element).Uri)));
}
}
public void DidReceiveScriptMessage(WKUserContentController userContentController, WKScriptMessage message)
{
var eventArgs = message.Body.ToString().ParseEventArgs();
switch (eventArgs.name)
{
case "invokeAction":
((HybridWebView)Element).InvokeAction(eventArgs.payload);
break;
case "invokeQRAction":
((HybridWebView)Element).InvokeQRAction();
break;
}
}
}
}
The problem here is probably with your Javascript.
Mobile and older devices often suppress the console errors of Javascript and instead of an error page or an exception, further Javascript is not executed and it seems as if it is not executed at all.
Especially with complex Javascript with many usings and references it is enough if there is a problem with one reference, so you don't see anything.
Here it can help to simplify the Javascript and to rebuild it bit by bit to localize the error.
I have an architecture where I am having a webview in MainActivity of my Android app. A page having a "Take Photo" button loads whenever user opens the app. On clicking "Take Photo" button, javascript will call dispatchTakePictureIntent() method defined in the Android app, which will redirect user to the Camera. Once, the user clicks the photo and submits it, I want to send the photo back to JS which in turn will make a AJAX call to the server to store the image.
I am facing trouble in developing the flow once user submits the photo. In my current implementation, I am able to store the image file locally and retrieve a file path, but I am unable to figure out how to use this file path in JS to get the file and send it on the server. Kindly help me out with this.
I have taken reference from this article: https://developer.android.com/training/camera/photobasics#TaskPath
MainActivity.java
public class MainActivity extends Activity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final String FILE_PATH_PREFIX = "file:";
private String imageFilePath;
private String callbackFunction;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidPlatform.setUp(this, APPLICATION_NAME);
setContentView(R.layout.activity_main);
webView = (WebView) findViewById(R.id.webview);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setGeolocationEnabled(true);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setDatabaseEnabled(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
webView.addJavascriptInterface(this, "Android");
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("URL to the page having take photo button");
}
#JavascriptInterface
public void dispatchTakePictureIntent(String _callbackFunction) {
this.callbackFunction = _callbackFunction;
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
File photoFile = createImageFile();
if (photoFile != null) {
this.imageFilePath = FILE_PATH_PREFIX + photoFile.getAbsolutePath();
Uri photoURI = FileProvider.getUriForFile(this,
"com.example.fileprovider",
photoFile);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
} else {
Toast.makeText(getApplicationContext(), R.string.please_retry, Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), R.string.no_camera_found, Toast.LENGTH_SHORT).show();
}
}
private File createImageFile() {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "storephoto_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = null;
try {
image = File.createTempFile(imageFileName,".jpg", storageDir);
} catch (IOException e) {
Log.e(TAG, "Exception in createImageFile:", e);
}
return image;
}
#TargetApi(Build.VERSION_CODES.KITKAT)
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE) {
if(resultCode == RESULT_OK && callbackFunction != null && imageFilePath != null) {
// What to do with imageFilePath?
//
// How to use it in Javascript to read and send image to backend server?
//
// Sample code if we send imageFilePath to JS:
// String callbackModule = String.format(TAKE_PICTURE_JS_MODULE, callbackFunction, imageFilePath);
// webView.evaluateJavascript(callbackModule, null);
}
}
}
}
Javascript
$takePhotoButton.click(function(e) {
e.preventDefault();
Android && Android.dispatchTakePictureIntent("takePhotoCallbackFn");
});
Note: Here it is necessary that user submits the photo through camera only and not via choosing/uploading an existing file.
I want to load to a about.html page inside asset folder by clicking a button in index.html inside android webview.
Here's the code:
Button:
About
Java:
WebView browser = (WebView) findViewById(webview);
browser.getSettings().setJavaScriptEnabled(true);
browser.setWebChromeClient(new WebChromeClient());
browser.loadUrl("file:///android_asset/www/index.html");
browser.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
But the problem is when i click on button it doesn't load about.html but if I add a javascript function with below code it works.. but i want to use href.
Code:
<button onclick="about()">About</button>
<script>
function about() {
location.href = "about.html";
}
</script>
How do I solve it?
write an interface for TagHandler and in your fromHtml method check for the tag and handle it by loading the page
https://developer.android.com/reference/android/text/Html.html
try this code:
private void loadWebView(WebView webView,String htmlString)
{
try {
final String mimeType = "text/html";
final String encoding = "UTF-8";
WebViewClient yourWebClient = new WebViewClient()
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
// This line we let me load only pages inside Webpage
if ( url.contains("") == true )
// Load new URL Don't override URL Link
return false;
// Return true to override url loading (In this case do nothing).
return true;
}
};
// Get Web view
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(yourWebClient);
// Load URL
webView.loadDataWithBaseURL("", htmlString, mimeType, encoding, "");
} catch (Exception e) {
e.printStackTrace();
}
}
use it as:
loadWebView(browser, "file:///android_asset/www/index.html") //pass url
Say, I set my WebView into example.com then I clicked on the page and load the example.com/about.
In the WebView I've injected Javascript to modify the HTML on the example.com, and it worked, and the problem is, how to inject another JavaScript to modify example.com/about. I mean how to inject multiple JavaScript to a multiple page of WebView?
public class MainActivity extends AppCompatActivity {
WebView mWebView;
private int getScale() {
Display display = ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int width = display.getWidth();
Double val = new Double(width) / new Double(100);
val = val * 100d;
return val.intValue();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
// Enable Javascript
WebSettings webSettings = mWebView.getSettings();
mWebView.setWebViewClient(new WebViewClient());
webSettings.setJavaScriptEnabled(true);
webSettings.setAllowUniversalAccessFromFileURLs(true);
mWebView.setWebViewClient(new WebViewClient());
mWebView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
// Inject CSS when page is done loading
injectCSS();
mWebView.loadUrl("javascript:var greeting = function (name) {\n" +
" console.log(\"Great to see you,\" + \" \" + name);\n" +
"};");
super.onPageFinished(view, url);
//Inject JS to edit html
injectScriptFile(view, "script.js"); // see below ...
// test if the script was loaded
view.loadUrl("javascript:setTimeout(test(), 500)");
}
private void injectScriptFile(WebView view, String scriptFile) {
InputStream input;
try {
input = getAssets().open(scriptFile);
byte[] buffer = new byte[input.available()];
input.read(buffer);
input.close();
// String-ify the script byte-array using BASE64 encoding !!!
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
view.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var script = document.createElement('script');" +
"script.type = 'text/javascript';" +
// Tell the browser to BASE64-decode the string into your script !!!
"script.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(script)" +
"})()");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return false;
}
});
mWebView.loadUrl("example.com");
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDisplayZoomControls(false);
}
private void injectCSS() {
try {
InputStream inputStream = getAssets().open("style.css");
byte[] buffer = new byte[inputStream.available()];
inputStream.read(buffer);
inputStream.close();
String encoded = Base64.encodeToString(buffer, Base64.NO_WRAP);
mWebView.loadUrl("javascript:(function() {" +
"var parent = document.getElementsByTagName('head').item(0);" +
"var style = document.createElement('style');" +
"style.type = 'text/css';" +
// Tell the browser to BASE64-decode the string into your script !!!
"style.innerHTML = window.atob('" + encoded + "');" +
"parent.appendChild(style)" +
"})()");
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mWebView.saveState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
mWebView.restoreState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu); // Add menu items, second value is the id, use this in the onCreateOptionsMenu
menu.add(0, 1, 0, "Back");
menu.add(0, 2, 0, "Refresh");
menu.add(0, 3, 0, "Forward");
getMenuInflater().inflate(R.menu.menu_main, menu);
return true; // End of menu configuration
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 3: //If the ID equals 3 , go forward
mWebView.canGoForward();
item.setIcon(R.drawable.forward);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) { // Enables browsing to previous pages with the hardware back button
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) { // Check if the key event was the BACK key and if there's history
mWebView.goBack();
return true;
} // If it wasn't the BACK key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
}
I am loading a webpage in WebView. There is a link in the webpage, which on desktop will download the file, but in the app the link should display a Toast saying the link is disabled for the app.
I am not sure how to get the value from href of the anchor tag, when the link is clicked.
<a class="btn btn-primary" download="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3" href="http://xx.xxx.com/wp-content/uploads/2015/11/abc-27-15.mp3">
<i class="fa fa-download"></i> Download Audio</a>
Can someone share an idea or any sample code on how to do this.
EDIT:1
Here is what I am doing currently:
private static final String URL = "http://xx.xxx.com/wp-content/uploads/";
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
String extra = hr.getExtra();
if (extra != null && extra.startsWith(URL) && extra.endsWith(".mp3")) {
Log.d("WebviewActivity", "Extra: " + extra);
Log.d("WebviewActivity", "Contains URL");
return true;
}
}
return false;
}
});
The problem with this approach is:
When i click on the link, i get the url in extra. It works fine till here. But, from next time, no matter where i click on the webview, the same extra is being returned. So even if i click on an image after i click on the url, i get the same url in the extra. Not sure if i doing anything wrong. Or is this the correct approach.
Please let me know if you need any details.
EDIT:2
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.
if (url != null) {
Log.d(TAG, "URL: "+url);
}
}
};
webView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
WebView.HitTestResult hr = ((WebView) v).getHitTestResult();
if (hr.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE) {
Message msg = mHandler.obtainMessage();
webView.requestFocusNodeHref(msg);
}
}
return false;
}
});
webView.loadUrl(mUrl);
}
Now, i get the URL that is clicked in the last action_down event. How to get the current URL?
EDIT 3 (Attempt with webviewclient:
private class MyWebViewClient extends WebViewClient {
private static final String URL = "xx.xxx.com/wp-content/uploads/";
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (!isFinishing())
mProgressDialog.show();
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
mProgressDialog.dismiss();
}
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
Toast.makeText(WebviewActivity.this,
"Please check your internet " + "connection and try again",
Toast.LENGTH_SHORT).show();
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.d("xxx", "Url: " + url);
if(url.contains(URL)) {
Log.d("xxx", "Url Contains: " + URL);
return true;
}
return false;
}
}
mMyWebViewClient = new MyWebViewClient();
webView.setWebViewClient(mMyWebViewClient);
Output in logcat when the link is clicked:
03-01 15:38:19.402 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:553] focusedNodeChanged: isEditable [false]
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:253] updateKeyboardVisibility: type [0->0], flags [0], show [true],
03-01 15:38:19.428 19626-19626/com.xx.xxx D/cr_Ime: [ImeAdapter.java:326] hideKeyboard
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:56] isActive: true
03-01 15:38:19.429 19626-19626/com.xx.xxx D/cr_Ime: [InputMethodManagerWrapper.java:65] hideSoftInputFromWindow
Because you are using a WebView and the link is not Java script this is very easy to achieve with a WebViewClient which you can use to monitor your WebView
myWebView.setWebViewClient( new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// check something unique to the urls you want to block
if (url.contains("xx.xxx.com")) {
Toast.make... //trigger the toast
return true; //with return true, the webview wont try rendering the url
}
return false; //let other links work normally
}
} );
It's possible that because your URL ends in .mp3 the file is being treated as a resource. You should also override the shouldInterceptRequest method of the WebViewClient to check this.
#Override
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
Log.d("XXX", "Url from API21 shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
public WebResourceResponse shouldInterceptRequest (WebView view, String url) {
Log.d("XXX", "Url from shouldInterceptRequest : " + url);
if (url.contains(URL)) {
return new WebResourceResponse("text/html", "UTF-8", "<html><body>No downloading from app</body></html>");
} else {
return null;
}
}
Most of the work can be done at the web page side itself. You have to write java script to identify which device is accessing the page (mobile, desktop etc) if its mobile then use java script binding technique to call the native android code to show Toast message.
http://developer.android.com/guide/webapps/webview.html
WebView webView = (WebView) findViewById(R.id.webview);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
WebAppInterface.java
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_SHORT).show();
}
}
YourHTML Page (this sample got a button click)
<input type="button" value="Say hello" onClick="showAndroidToast('Hello
Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>