"Android" detects if it is in a WiFi environment and uses WebView to implement the browser app

Source: Internet
Author: User
Tags gettext

Since the webview of Android comes packaged in many ways, the browser app is relatively simple to implement.

The only difficulty is that you need to supplement the loading progress bar with some buttons while judging whether the user is entering a URL,

As shown,

When open, if not in the WiFi environment give a warning

The use of WebView to achieve a simple browser, the user did not enter the URL when the prompt, with the forward, backward, refresh, stop, jump function.


There is a progress bar when loading the Web page. Basically, it's a simple browser.

The production process is as follows:

1, first set the characters of each component in Res\values\strings.xml, the name of the app, as follows:

<?xml version= "1.0" encoding= "Utf-8"?><resources>    <string name= "app_name" > Browser </string >    <string name= "action_settings" >Settings</string>    <string name= "Button1" > Forward </ string>    <string name= "Button2" > Back </string>    <string name= "Button3" > Refresh </string>    <string name= "Button4" > Stop </string>    <string name= "Button5" >go!</string></ Resources>

2, then modify the Res\values\styles.xml, in the inside set a untitled bar app style, the app's style settings in the "Android" app transparency and font color notconsistent, context menu (click to open the link) has already said, here no longer repeat.

<resources xmlns:android= "Http://schemas.android.com/apk/res/android" >    <style name= "Notitle" >        <item name= "Android:windownotitle" >true</item>    </style></resources>

3, after the Androidmanifest.xml application testing Equipment network environment and the use of network permissions, while modifying the app's style for the notitle we just defined, modified as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/ Android "package=" Com.browser "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk Android oid:minsdkversion= "8" android:targetsdkversion= "/> <uses-permission android:name=" Android.permission.A Ccess_network_state "/> <!--ask for device current network status--<uses-permission android:name=" Android.permission.INTERNET "/> <!--requires connection to network--<application android:allowbackup=" true "android:icon=" @drawable/ic_launc        Her "android:label=" @string/app_name "android:theme=" @style/notitle "> <!--Use the Notitle style in style--            <activity android:name= "com.browser.MainActivity" android:label= "@string/app_name" > <intent-filter> <action android:name= "Android.intent.action.MAIN"/> &L T;category android:name= "android.intent.caTegory. LAUNCHER "/> </intent-filter> </activity> </application></manifest>
4, then modify the layout of mainactivity in Res\layout\activity_main.xml. Place a top-down vertical linear layout in which to place: a message processing between "Android" progress bar and thread (click Open link) already mentioned progress bar component, a horizontal linear layout, the five buttons inside can use "Android" Using the relative layout to update the software's style as the activity of the theme dialog, using the Layout_weight attribute to the table layout of the row division (click the Open link) to achieve its equal, so as to get better results, there is no such place, The effect on the real machine is that all buttons are left aligned, an input box for the user to enter the URL, and finally a browser component covering the entire screen WebView, the code is as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" android:layout_width= "Match_parent" android:layout_height= "match_parent" android:orientation= "vertical" > <progressbar android:id= "@+id/pro GressBar1 "style="? Android:attr/progressbarstylehorizontal "Android:layout_width=" Match_parent "Andro id:layout_height= "Wrap_content"/> <linearlayout android:layout_width= "Match_parent" android:layout             _height= "wrap_content" android:orientation= "horizontal" > <button android:id= "@+id/button1" Android:layout_width= "Wrap_content" android:layout_height= "wrap_content" android:text= "@ String/button1 "/> <button android:id=" @+id/button2 "android:layout_width=" wrap_content            "Android:layout_height=" wrap_content "android:text=" @string/button2 "/> <button Android:id= "@+id/button3 "android:layout_width=" Wrap_content "android:layout_height=" Wrap_content "android:text= "@string/button3"/> <button android:id= "@+id/button4" android:layout_width= "Wrap_conte            NT "android:layout_height=" Wrap_content "android:text=" @string/button4 "/> <button Android:id= "@+id/button5" android:layout_width= "wrap_content" android:layout_height= "Wrap_con Tent "android:text=" @string/button5 "/> </LinearLayout> <edittext android:id=" @+id/edi TText1 "android:layout_width=" match_parent "android:layout_height=" wrap_content "android:inputtype=" t Ext "/> <webview android:id=" @+id/webview1 "android:layout_width=" Match_parent "Android:layo ut_height= "Match_parent"/></linearlayout>

5, the last is Mainactivity.java modification, logic is very simple, get each component, set its implementation method, the specific implementation method in the code has been labeled. In Java to determine whether user input is a URL, in the "Java" using regular expressions to determine whether it is a URL (click to open the link) has said here not to repeat.

Package Com.browser;import Java.util.regex.pattern;import Android.net.connectivitymanager;import Android.net.networkinfo;import Android.os.bundle;import Android.annotation.suppresslint;import Android.app.activity;import Android.app.alertdialog;import Android.view.keyevent;import Android.view.View;import Android.view.view.onclicklistener;import Android.view.view.onkeylistener;import android.webkit.WebChromeClient; Import Android.webkit.webview;import Android.webkit.webviewclient;import Android.widget.button;import Android.widget.edittext;import Android.widget.progressbar;import Android.widget.toast;public class MainActivity Extends Activity {private ProgressBar progressbar1;private button button1;private button button2;private button button3; Private button Button4;private button button5;private EditText edittext1;private WebView webView1; @SuppressLint (" Setjavascriptenabled ") @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.laYout.activity_main);//Determine if you are in a WiFi environment Connectivitymanager Connectivitymanager = (connectivitymanager) getSystemService (Connectivity_service); Networkinfo networkinfo = Connectivitymanager.getnetworkinfo (Connectivitymanager.type_wifi); Networkinfo.isconnected ()) {Toast.maketext (Mainactivity.this, "not currently in the WiFi environment, please pay attention to your traffic!) ", Toast.length_short). Show ();} Get Component ProgressBar1 = (ProgressBar) Findviewbyid (r.id.progressbar1); button1 = (Button) Findviewbyid (R.id.button1); Button2 = (Button) Findviewbyid (r.id.button2), Button3 = (button) Findviewbyid (r.id.button3); button4 = (Button) Findviewbyid (r.id.button4); button5 = (Button) Findviewbyid (r.id.button5); editText1 = (EditText) Findviewbyid ( R.ID.EDITTEXT1); webView1 = (WebView) Findviewbyid (R.ID.WEBVIEW1);//set JavaScript to be available and process JavaScript popup// There is no @suppresslint ("setjavascriptenabled") at the beginning of the method, and there is a warning webview1.getsettings () that a cross-site attack may occur xxs. setjavascriptenabled ( true);//Set Load progress bar webview1.setwebchromeclient (new Webchromeclient () {@Overridepublic void OnprogresschanGed (WebView view, int newprogress) {super.onprogresschanged (view, newprogress); if (newprogress = = 100) { Progressbar1.setvisibility (view.invisible);} else {if (view.invisible = = Progressbar1.getvisibility ()) {progressbar1.setvisibility (view.visible);} Progressbar1.setprogress (newprogress);}}); Webview1.setwebviewclient (New Webviewclient ());//Do not use the built-in browser//Forward button Button1.setonclicklistener (new Onclicklistener () { @Overridepublic void OnClick (View arg0) {webview1.stoploading ();//stop loading the current URL webview1.goforward ();//Call the encapsulated forward method string url = Webview1.geturl ();//Gets the Urledittext1.settext (URL) of the page after loading;//populated Address bar}});//Back button Button2.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {webview1.stoploading ();//stop loading the current URL webview1.goback ();// Call the encapsulated fallback method string url = Webview1.geturl (),//Get the Urledittext1.settext (URL) of the page after loading,//fill in the Address Bar}});// Refresh button Button3.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {webview1.stoploading ( ); Webview1.reload ();}); /Stop Buttons button4.setOnClickListener (New Onclicklistener () {@Overridepublic void OnClick (View arg0) {webview1.stoploading ();}}); /Enter the time to press the ENTER key Edittext1.setonkeylistener (new Onkeylistener () {@Overridepublic Boolean onKey (View arg0, int keycode, KeyEvent arg2) {if (keycode = = keyevent.keycode_enter) {String URL = edittext1.gettext (). toString (); Pattern pattern = Pattern.compile ("^ ([hh][tt]{2}[pp]://|[ hh][tt]{2}[pp][ss]://) (([a-za-z0-9-~]+).) + ([a-za-z0-9-~\\/]) +$ "); if (!pattern.matcher (URL). Matches ()) {URL =" http://"+ URL;} if (Pattern.matcher (URL). Matches ()) {webview1.loadurl (URL);} else {new Alertdialog.builder (mainactivity.this). Setmessage ("Please enter the URL!") "). Setnegativebutton (" OK ", null). Show ();}} return false;}); /Go To button Button5.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View arg0) {String URL = Edittext1.gettext (). toString (); Pattern pattern = Pattern.compile ("^ ([hh][tt]{2}[pp]://|[ hh][tt]{2}[pp][ss]://) (([a-za-z0-9-~]+).) + ([a-za-z0-9-~\\/]) +$ "); if (!pattern.matcher (URL). Matches ()) {url = "http://" + URL;} if (Pattern.matcher (URL). Matches ()) {webview1.loadurl (URL);} else {new Alertdialog.builder (mainactivity.this). SetIcon (R.drawable.ic_launcher). Settitle (R.string.app_name). Setmessage ("Please enter the URL! "). Setnegativebutton (" OK ", null). Show ();}});}}

At this point, the entire app was written, I uploaded a code, we are interested to see: http://download.csdn.net/detail/yongh701/8902617

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Android" detects if it is in a WiFi environment and uses WebView to implement the browser app

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.