Android как скопировать url из webview
Перейти к содержимому

Android как скопировать url из webview

Как скачать файлы с webview Android?

мой код ниже загружает страницу url в порядке, и после поиска песни, когда я нажимаю на ссылку для загрузки, она падает. Существует не так много учебников о том, как заставить менеджер загрузок работать с webview. Что я делаю не так?

3 ответов

это может быть зависит от проблемы версии сборки android, приведенный ниже код будет успешно работать на сборках 2.3+, проверьте это,

вы добавили разрешение DownloadManager в файл манифеста?

——редактировать——

я копирую фрагмент кода для вашей справки из браузера Android stock при запуске задачи загрузки:

также не забудьте добавить ниже код в манифест.xml-файл, его очень важно, это даст ему разрешение на сохранение в хранилище так же, как дает ему разрешение на Интернет для weview.

Technology Tutorials

There are 2 different ways to get html content from android webview.

1) Using Javascript
In this approach, url will be loaded by webview itself. Means each and every url will be invoked in the webview context. so webview will manage cookies and http session automatically.

2) Using Java only to get html content from webview.
In this approach, webview will not be responsible for fetching the content from remote servers. We have to handle invocation of urls and have to fetch html content using code and then we can perform whatever operations we require on content before setting it in the webview.
So maintaining cookies and http session will be our responsibility.
In the example snippet below for this approach will show a workaround for maintaining http session.

First you have to configure javascript interface for webview, using below method

Here 1st parameter is the MyJavaScriptInterface class, that you have to write as below.
and 2nd parameter is the name of the javascript object you will use to call the method you write (showHTML).

Note that annotation ‘ @JavascriptInterface’ on the showHTML method. it is mandatory to work this propertly for android >=4.2.
Another thing to keep in mind is that, from showHTML method, you will not able to access other components of your activity directly. You have to post runnable objects to a handler. and write all the logic to access activity’s components inside the run method of runnable.

Now everyting is setup. You just have to call showHTML method explicitly when the page loading is finished into the webview.
For this you have to implement WebviewClient which will be notified by android once page is loaded into the webview, and from that you can invoke showHTML method using javascript and pass the html content loaded into webview.
This can be achieved using below code.

Below is the complete activity code you can refer to if anything is missed in above code snippet.

If you are using proguard while exporting your apps then following properties must be included in proguard-project.txt (proguard config file) .

2) Using Java only to get html content from webview.

In this approach, you have to handle page loading events (page loading started, page loading finished) of webview based on your requirements and from there you have to use httpclient api to actually hit the url and get the content.
this way you will have the access to the html content returned by remote server and you can modify the content as per your needs before/after it is rendered into the webview.

Below is the complete code for this.

As stated above, this approach will not maintain cookies and http sessions.

So if you don’t have requirement to maintain http session, then above code snippet is sufficient. Otherwise you have to implement additional code to achieve session management.
This is how you can achieve it.

First thing is you have to make your httpclient instance global. Means, you have to use same http client for executing each and every request.
Also you have to create global HttpContext and CookieStore objects, which will be used for executing http requests.

You can use below method to initialize the httpclient.

Now you have to execute each and every request in localContext, which is using cookieStore internally.
And after invoking the request urls, you have to call below method to sync the cookies with webview.

Getting the HTML source from an Android WebView

On and off I’m working on writing an Atom/RSS feed reader for Android. The feed reader is using an Android WebView to display the contents of a feed and to be able to debug some issues I had I wanted to be able to view the HTML source for a page.

That’s should be simple I though, just do WebView.getData() and show it in a dialog. But no, there’s no method to get the HTML source from a WebView, so one has to jump through a lot of hoops to do that. Also the examples I found uses WebView.addJavaScriptInterface to do its job which is not such a good idea because addJavaScriptInterface has security problems and doesn’t even work on Android 2.3. And I do want my application to run on fairly old Android devices (I still use a Motorola Defy at work, I like the form factor and that it’s waterproof).

So after a bit of thinking I figured out an easier way of getting the source. There is a class called WebViewClient which among other things can be used to override what should happen when a follows a link in the WebView. This together with a bit of JavaScript can be used to get the source.

First, when initializing the WebView, tell it to use a custom WebViewClient:

When asked to view the source, enable JavaScript for the WebView and then inject a bit of JavaScript which builds and follows an URL containing the HTML:

The custom WebViewClient will catch this URL:

And we can finally show the source in a dialog:

As simple as that. And it seems to work on everything from Android 2.3 up to Android 4.4.

Although what we get from the WebView does not quite seem to be the source code it was fed to begin with. It seems that the WebView will fix up the HTML so that it is correct and will also decode any entitydefs. So for example if the WebView was fed “<p>Hello Wörld<p>” what we would get back is “<html><head></head><body><p>Hello Wörld<p></body></html>”. It’s still useful for what I wanted to do though.

Добавить комментарий

Ваш адрес email не будет опубликован.