Android browser with view source

WebView — создай свой браузер

Android позволяет создать собственное окно для просмотра веб-страниц или даже создать свой клон браузера при помощи элемента WebView. Сам элемент использует движок WebKit и имеет множество свойств и методов. Мы ограничимся базовым примером создания приложения, с помощью которого сможем просматривать страницы в интернете. В последних версиях используется движок от Chromium, но большой разницы в этом нет для простых задач.

Создадим новый проект MyBrowser и сразу заменим код в файле разметки res/layout/activity_main.xml:

Теперь откроем файл активности MainActivity.java и объявим компонент WebView, а также инициализируем его — включим поддержку JavaScript и укажем страницу для загрузки.

Так как приложение будет использовать интернет, необходимо установить разрешение на доступ к интернету в файле-манифесте.

Там же в манифесте модифицируем строчку для экрана, удалив заголовок из нашего приложения (выделено жирным):

Запустим приложение. В нашем распоряжении появился простейший вьювер веб-страниц, но с одним недостатком. Если вы щёлкнете на любой ссылке, то у вас автоматически запустится браузер по умолчанию и новая страница отобразится уже там. Точнее так было раньше. На новых устройствах при запуске приложения сразу открывается браузер.

Чтобы решить данную проблему и открывать ссылки в своей программе, нужно переопределить класс WebViewClient и позволить нашему приложению обрабатывать ссылки. Добавим в коде вложенный класс:

Затем в методе onCreate() определим экземпляр MyWebViewClient. Он может находиться в любом месте после инициализации объекта WebView:

Теперь в нашем приложении создан WebViewClient, который позволяет загружать любой указанный URL, выбранный в WebView, в сам контейнер WebView, а не запускать браузер. За данную функциональность отвечает метод shouldOverrideUrlLoading(WebView, String), в котором мы указываем текущий WebView и нужный URL. Возвращаемое значение true говорит о том, что мы не нуждаемся в запуске стороннего браузера, а самостоятельно загрузим контент по ссылке. В версии API 24 добавили перегруженную версию метода, учитывайте это обстоятельство.

Повторно запустите программу и убедитесь, что ссылки загружаются теперь в самом приложении. Но теперь возникла ещё одна проблема. Мы не можем вернуться к предыдущей странице. Если мы нажмём на кнопку «BACK» (Назад) на устройстве, то просто закроем своё приложение. Для решения новой проблемы нам необходимо обрабатывать нажатие кнопки «BACK». Добавляем новый метод:

Мы должны проверить, что WebView поддерживает навигацию на предыдущую страницу. Если условие верно, тогда вызывается метод goBack(), который возвращает нас на предыдущую страницу на один шаг назад. Если таких страниц набралось несколько, то мы можем последовательно вернуться к самой первой странице. При этом метод всегда будет возвращать значение true. Когда мы вернёмся на самую первую страницу, с которой начали путешествие по интернету, то вернётся значение false и обработкой нажатия кнопки BACK займётся уже сама система, которая закроет экран приложения.

Запустите приложение ещё раз. У вас появился свой собственный веб-браузер, позволяющий ходить по ссылкам и возвращаться на предыдущую страницу. Изучив документацию, вы можете оснастить приложение и другим вкусными плюшками для своего браузера.

Если вам нужно часть ссылок, ведущих на ваш сайт открывать в браузере, а локальные ссылки открывать в приложении, то применяйте условие с разными возвращаемыми значениями.

Универсальный метод, который все локальные ссылки откроет в приложении, остальные в браузере (меняем одну строчку):

А сейчас немного усложним пример, чтобы у пользователя появилась альтернатива стандартным браузерам.

Чтобы было понятнее, переделаем пример следующим образом. Создайте две активности. На первой активности разместите кнопку для перехода на вторую активность, а на второй активности разместите компонент WebView.

Читайте также:  Работы для android программистов

В манифесте прописываем у второй активности фильтр.

Код для кнопки для перехода на вторую активность.

Мы создали собственное намерение с указанием фильтра и предоставили данные — адрес сайта.

Вторая активность должна принять данные:

В фильтре для второй активности мы указали два действия.

Это означает, что любые активности (читай, приложения) могут вызвать вашу активность с мини-браузером по такому же принципу. Запустите в студии в отдельном окне любой старый проект или создайте новый и добавьте в него кнопку и пропишите тот же код, который мы использовали для щелчка кнопки.

Запустите второе приложение (первое приложение можно закрыть) и нажмите на кнопку. У вас запустится не первое приложение с начальным экраном, а сразу вторая активность с мини-браузером. Таким образом, любое приложение может запустить браузер, не зная имени класса вашей активности, а используя только строку «ru.alexanderklimov.Browser», передаваемую в Intent. При этом ваша активность с браузером должна иметь категорию по умолчанию и данные. Напомню:

Вы можете представить свою строку в виде строковой константы и сообщить всем потенциальным пользователям вашего браузера, как они могут запустить его у себя. Но в Android уже есть такая готовая константа ACTION_VIEW, которая по справке документации представляет собой следующее:

Перепишем код для кнопки у второго приложения

Что произойдёт на этот раз? Мы помним, что у нас прописано два действия, включая и android.intent.action.VIEW. А значит наше первое приложение с браузером тоже должно распознавать эту команду, когда какое-то приложение у пользователя использует этот код. На эмуляторе как минимум есть одна такая программа «Browser», и теперь к ней добавилась наша вторая активность из первого приложения. На экране появится выбор из двух приложений.

А если удалить все альтернативные браузеры и оставить только вашу программу, то и выбора не будет. Ваш браузер станет основным. И если какое-то приложение захочет запустить веб-страницу указанным способом, то откроется ваша программа.

Небольшое замечание. Если заменить последнюю строчку на такую:

То в окне выбора программы вместо верхней строки «Open with» или её локального перевода появится ваша строка. Но не это главное. Если по каким-то причинам на устройстве не окажется ни одного браузера, то данный вариант кода не вызовет краха приложения, в отличие от первоначального варианта. Поэтому используйте предложенный вариант ради надёжности.

Источник

7 Best Open Source Browser for Android (2018)

Though most browsers for Android are free and filled with features, they are not open source. One of the best things about open source apps is that you can actually look for the code behind it. More often than not, these open source apps have features that are sorely lacking in the regular apps. If you knew enough, you can even fork and make your own version without much effort. If you are someone who likes to use open source apps then here are some of the best free and open source Android browsers you should try.

Open Source Browsers for Android

1. Brave

Brave is a relatively new and fast-growing browser that is not only available for Android but also for desktop users. The main moto of Brave is that it is fast, secure, and private browser that doesn’t violate your privacy. It backs up the moto using useful features like built-in ad-blocker, battery optimization, HTTPS Everywhere, 3rd party cookie blocking, script blocking, etc. What I like about Brave browser is the dashboard where it shows how many ads, trackers and scripts were blocked. There is also a built-in data optimization feature that blocks data-intensive things like images, videos, etc., to save data consumption.

Читайте также:  Как разблокировать андроид комбинация

Although, we don’t recommend this, but if you are someone often browse shady websites (like torrents, surveys and adult forums) Brave blocks almost everything except the main content. Therefore giving you smooth experience that one can get.

Another reason to use brave browser is that, unlike most apps that you will see in this list, Brave is the only one which is available on all platform. Meanwhile, you can use it as your primary browser and it’ll sync all your data on mobile and desktop.

Since Brave is built ground up to be fast, it is obviously faster than the default Chrome browser on your Android. Of course, Brave still uses the underlying Chromium Blink engine to render web pages. Overall, if you are looking for open source alternative to chrome, go for Brave browser.

Price: Free.

2. Firefox Focus

Firefox Focus is a tiny little open-source browser that weighs less 5 MB. Consider it like incognito window of Chrome but with no tabs or bookmarking feature.

Like most open source browser for Android, it automatically blocks ads, blocks trackers. But what differentiate Firefox focus from the rest is that it automatically deletes your browsing history and clears cookies, the moment you exit the browser. and even erase your browsing history, passwords, and cookies with a single tap or as soon as you close the browser.

Since Firefox Focus is very lightweight, don’t expect the regular features you would find on a regular mobile browser. For instance, it doesn’t have bookmarking features, find in page, and there are almost no customization options whatsoever. Add to that, some websites may not work as they should due to aggressive blocking. But, if you value your privacy don’t mind the inconvenience then give Firefox Focus a try.

Pro Tip: Set Firefox Focus as your default browser. That way, when you click links on your Reddit app or email etc it will quickly open in Focus. And you don’t have to worry about any tracking as well.

Price: Free.

3. Zirco Browser

Zirco is a very simple and straightforward open source browser that has all the usual features like bookmarks, history, downloads manager, etc. It also has a built-in ad-blocker to save data and protect you from the unwanted tracking, threats, and data consumption.

The user interface of Zirco is not the best and looks dated. It can take some time to get used to working with Zirco because of its odd user interface choices. For instance, to access the settings menu, you have to tap on the menu icon (three vertical dots) appearing next to the navigation buttons at the bottom of the screen. Which is a very odd placement compared to current Android app designs.

Nevertheless, Zirco gets the job done with flying colors when it comes to the browsing experience.

Price: Free.

4. Lightning Browser

The Lightning browser is another lightweight and fast open-source browser for Android that is less than 3MB. Even though the browser is lightweight than Firefox Focus, it has all the regular features like browsing history, support for tabs, bookmarks, built-in Adblock, search suggestions, support for full screen, etc. Interestingly, the app also has a good reading mode which removes all the distractions of a web page. Moreover, you can also switch between different user agents with just a single click. The app also supports TOR Orbit proxy. For better privacy, you can even switch between built-in search engines like DuckDuckGo and Startpage.

Читайте также:  Как обновить или перепрошить андроид

Another reason you should try lightning browser is when you are using Orbot to browse anonymously, It automatically activate when you detect Orbot. So, if you don’t like Orweb that comes along with Orbot, give Lightning browser a try.

Price: The app is free and it is limited to ten tabs in any given browsing session. For extra features like ad-block and unlimited tabs, you need to purchase the pro version for around $1.5.

5. Privacy Browser

Just like Firefox Focus, Privacy Browser is mainly developed to protect your information from surprises. However, unlike Firefox Focus, Privacy browser is filled with useful features like the ability to block the first party and third party cookies, ability to disable DOM storage, block trackers and ads, support for Tor Orbot proxy, full-screen browsing, SSL pinning, etc.

Of all the features, the one I really like is the ability to set specific settings for each and every domain. For instance, you may not want certain websites to run scripts, you want to allow certain websites to store cookies, etc. In those situations, just visit the website, tap on the menu icon, select the option “Edit domain settings” and configure the options accordingly. Of course, there is a whole load of other options to configure the app’s global settings.

Most of all, the app’s user interface is very pleasant to use. If you are looking for a fully featured web browser that protects your privacy, open source and has a great user interface then Privacy Browser is a good choice.

Price: Free.

6. IceCatMobile

IceCatMobile is built upon Firefox. As such, rather than using the default Android Webview, IceCatMobile uses Gecko layout rending engine to render web pages. IceCatMobile comes with a built-in SpyBlock that can block trackers, ads, and third-party cookies, ability to protect you from JavaScript traps, HTTPS Everywhere to force HTTPS on all websites and the ability to counteract browser fingerprinting. Additionally, IceCatMobile also has support for plugins and add-ons.

The good thing about the add-ons and plugins of IceCatMobile is that they are all completely free.

Price: Free.

7. F|L|OSS Browser

Floss is yet another lightweight browser that weighs less than 3MB but has all the features you will ever need. Compared to other apps on this list, the user interface of Floss is unique but easy to use. Most of all, I really like the bottom address bar. In fact, all the options are neatly arranged at the bottom of the screen to make the navigation easier and faster.

Features of Floss include but not limited to support for unlimited tabs, quick tab switching, ability to take a screenshot of web pages, bookmarks, support for mobile and desktop user agents, multiple search engines, dark mode, etc.

Price: Free.

8. Yuzu Browser

Like Firefox Focus, Yuzu Tiny is also tiny and fast, yet it give you customization options like import and export bookmarks. You can also integrated hosts based ad-blocker.

Like Chrome home feature, Yuzu can also be customized to be bottom bar.

Comment below share your own favorite open source browsers for Android.

Источник

Оцените статью