Android Java - Get Plain Text From Webpage (alert System)
What I want to do should be very simple, however I have little to none Java/Android experience. I have a WebView setup in Eclipse. I want the webpage to go to http://example.com/my
Solution 1:
There's no straightforward way to do what you want, though it can be done. First, define an interface that goes something like:
publicinterfaceWebInterfaceDelegate {
publicvoidreceivedHtml(String html);
}
Then, define a class that you want to expose to the JavaScript runtime in your WebView, something along the lines of:
publicstaticclassWebViewJavaScriptInterface {
private WebInterfaceDelegate delegate;
publicWebViewJavaScriptInterface(WebInterfaceDelegate delegate) {
this.delegate = delegate;
}
publicvoidhtmlLoaded(String html) {
if (delegate != null) {
delegate.receivedHtml(html);
}
}
}
Then, make your Activity
implement the interface you defined above, like:
publicclassAndroidWebViewActivityextendsActivityimplementsWebInterfaceDelegate {
publicvoidonCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...WebView webView = (WebView)findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.addJavascriptInterface(newWebViewJavaScriptInterface(this), "AndroidAPI");
webView.loadUrl("http://your.url.com");
}
//...publicvoidreceivedHtml(String html) {
//inspect the HTML hereSystem.out.println("Got html: " + html);
}
}
Finally, add some JavaScript to your page that goes like:
<script>window.onload = function() {
AndroidAPI.htmlLoaded(document.body.innerHTML);
}
</script>
So you can do all that, or you can just use something like URL.openStream()
to connect directly to your target webpage and read the markup off of the socket instead of off of the WebView
. To do this is as simple as:
InputStreamresponse=newURL("http://example.com/mypage.php").openStream();
//read the data from the response into a buffer, then inspect the buffer
You can find some additional information here:
Post a Comment for "Android Java - Get Plain Text From Webpage (alert System)"