How to make your app browser android. The best browsers for Android. Additional installation of a web browser for transition to internal links

Dear, I am a student BCA. I have to make one project for the last semester. Therefore, I decided to create a web that works on the Android OS, but I am completely for this application. So, can anyone help me in this. I have already installed all the necessary tools, such as JDK, Android SDK 3.0, Eclipse. But now I have no idea where I should start developing a browser. Therefore, please help me ... I have only 2 months for this project. So is it possible after 2 months or not?

It depends on what you mean when developing a browser ...

Development of a browser mechanism + rendering from scratch is a lot of work, but you can easily create an Androids webview browser using WebViewClient and create a new user interface by changing the method of user interaction with the browser.

WebView has all sorts of interceptors to intercept interact with the browser, so you can easily expand it. For example, you can allow the user to overflow pages (for example, Google FastFlip), experimenting with 3D, making a displayed web page in OpenGL space (for example, in the browser of the sphere), etc.

As a starting point, take a look at the blog Alexander Kamek and his Mosambro project, which expands Android browser by adding micormat support.

It sounds like a really big project, and therefore you can't just start from scratch and write it down. You must compile a plan on how you want to implement all parts, record charts of classes, etc. If you are studying computer science, you should have heard about it in previous semesters.

First you have to ask yourself if this project is possible As you can see from comments, most people agree that you should not underestimate this task!

I really suggest you understand the scale of this task, here is the source code of the Androids browser, which gives you an idea of \u200b\u200bits complexity.

Creating a basic browser could be made every other day or two for those who have the experience of developing Android, as well as others stated that WebView provides almost everything you need to display a web page. There are several settings for JavaScript and other features for checking, and then after marking the main text box for the URL and the GO URL, which is largely the main web browser.

Real work comes in all extended settings. Creating a browser who competes with large guys maybe a little difficult for one person in a couple of months, but to do something that works, very possible. Try!

To create a complete web browser in Android you use WebView.

Simple binding code:

WebView WV \u003d (WebView) FindViewByid (R.ID.WebView1); WV \u003d (WebView) FindViewByid (R.ID.WebView1); WV.Loadurl ("http://www.apsmind.com");

Study Programming for Android I started not so long ago. After Eclips betrayed my first Hello Word, immediately wanted more: many plans and grand ideas arose. One such idea was to spell your browser. I think, many beginner programmers have had such a desire. These are the requirements of me were delivered and what happened in the end.

  • The program should open the links of the Global Network, to freely move on the pages and backwards;
  • Be able to download files and download back to the network;
  • Create bookmarks and save them;
  • Be able to download links sent from other applications;
  • There must be a home page button, a menu with various settings, etc.

In general, a full-fledged browser with your own hands. I will embody in the code.

The program is written on the basis of the standard WebView included in Android. I use Yandex as the starting page, this is a matter of taste. As the main ACTIVITY will be MainActivity.

First, I specify the markup of the XML file -Activity_main.xml. As the main container, we use LinearLayout - we wrap in it ProgressBar to display the boot process. Next, create another LinearLayout container - you wrap our WebView and FrameLayout (it is used to stretch the video playable on the entire screen).

View code

LinearLayout Xmlns: Android \u003d "http://schemas.android.com/apk/res/android" XMLNS: Tools \u003d "http://schemas.android.com/tools" Android: layout_width \u003d "match_parent" android: layout_height \u003d "Match_Parent" Android: Orientation \u003d "Vertical" Tools: Context \u003d ". MainActivity"\u003e

Let's write code in MainActivity

Full MainActivity code.

View full code

Import java.io.file; Import android.r.Menu; Import android.annotation.suppressLint; Import Android.app.actionBar; Import Android.app.ActiveIVITY; Import Android.app.Alertdialog; Import android.app.downloadManager; Import android.app.DownloadManager.Request; Import Android.app.KeyGuardManager; Import Android.app.SearchManager; Import android.content.broadcastReceiver; Import android.content.context; Import Android.Content.DialogInterface; Import android.Content.intent; Import android.content.intentFilter; Import Android.content.SharedPreferences; Import android.net.uri; Import android.os.Bundle; Import android.os.Environment; Import android.os.parcelable; Import android.os.powerManager; Import android.preference.preferenceEmanager; Import android.provider.mediaStore; Import android.util.log; Import Android.View.KEYEVENT; Import android.view.Menu; Import Android.view.MenuItem; Import Android.View.View; Import android.view.WindowManager; Import android.webkit.consoleMessage; Import android.webkit.downloadListener; Import android.WebKit.Valuecallback; Import Android.WebKit.WebbackForwardList; Import android.webkit.Webchromeclient; Import android.webkit.WebView; Import Android.webkit.WebViewClient; Import Android.Widget.FrameLayout; Import android.widget.SearchView; Import android.widget.Toast; Import Android.graphics.Bitmap; Import Android.Webkit.urlutil; public class MainActivity extends Activity (// Boolean status for compound Boolean isInternetPresent \u003d false; ConnectionDetector cd; private WebChromeClient.CustomViewCallback mFullscreenViewCallback; private FrameLayout mFullScreenContainer; private View mFullScreenView; private WebView mWebView; String urload; int cache \u003d 1; SharedPreferences sPref; Final Activity Activity \u003d This; Public URI Imageuri; Private Static Final Int FileChooser_Resultcode \u003d 2888; Private ValueCallback MuploadMessage; Private URI McapturedImageuri \u003d NULL; Private DownloadManager; @Override Protected Void OnCreate (SavedInstanceState); SetContentView (R.Layout.Activity_Main); // Create an example of the Connection Detector class: CD \u003d New ConnectionDeter (getApplicationContext ()); // Create a Home Final ActionBar actionBar \u003d getActionBar (); actionBar.setHomeButtonEnabled (true); actionBar.setDisplayHomeAsUpEnabled (true); // catch the intent that the file is loaded and notifies BroadcastReceiver receiver \u003d new BroadcastReceiver () (@Override public void onReceive (Context context, intent intent) (String Action \u003d Intent.GetAction (); if (downloadmanager.action_download_complete.equals (Action)) (Loadend ();))); // Fishing Intent that the file is loaded RegisterReiver (Receiver, New IntentFilter (downloadManager.Action_Download_Complete)); MWEBVIEW \u003d (R.ID.Web_View); MfullScreenContainer \u003d (FrameLayOut) FindViewByid (R.ID.FullScreen_Container); MWebView.setWebchromeClient (MWebChromeclient); MWebView. Loadurl ("http://yandex.ru"); HandleIntent (getIntent ()); class HelloWebViewClient extends WebViewClient (@Override public void onPageStarted (WebView view, String url, Bitmap favicon) (super.onPageStarted (view, url, favicon); findViewById (R.id.progress1) .setVisibility (View.VISIBLE); setTitle ( url); urload \u003d mwebview.geturl (); ConnectingTointernet ();) @Override public boolean shoulderrideurLoading (view.Loadurl (URL); // Run Links to the URI URI \u003d URI.PARSE (URL ); if (uri.getscheme (). Equals ("Market") (Android.Content.intent.action_View); i.SetData (URI); i.Addflags (intent.flag_activity_new_task); startactivity (i); mwebview.cangoback (); (mwebview.goback ();)) // Run Email if (uri.getscheme (). Equals ("MailTo")) (INTENT I \u003d New Intentent (Android.Content.intent .Action_send); i.setType ("text / html"); i.Putextra (Intent.Extra_Subject, "Enter theme"); i.Putextra (Intent.Extra_Text, "Enter the text"); i.Putextra (Intent.Extra_Email , New String (URL)); startAct ivity (i); mwebview.cangoback (); (MWebView.goback ();)) // Run the IF call (URI.Getscheme (). Equals ("Tel") (INTENT I \u003d New Intent (Android.Content.intent.action_dial); I.SetData (URI) ; startatoryivity (i); mwebview.cangoback (); (MWebView.goback ();)) // Run Loping if (uri.getscheme (). Equals ("Geo")) (Intent i \u003d New Intent (Android.Content . INTENT.Action_View); I.SetData (URI); Startatoryivity (I); mwebview.cangoback (); (MWebView.goback ();)) Return True; @Override public void onpagefinished (FindViewByid (R.ID.progress1) .Setvisibility (View.Gone);) @Override Public Void OnreceiveDerror (Webview View, Int Errorcode, String Description, String Failingurl) ( ConnectingTointernet (); mwebview.loadurl ("file: ///android_asset/error.png");)) MWebView.setWebViewClient (New HelloweBViewClient ()); // load the files on the device mWebView.setDownloadListener (new DownloadListener () (@Override public void onDownloadStart (final String url, String userAgent, String contentDisposition, String mimetype, long contentLength) (final String fileName \u003d URLUtil.guessFileName (url, contentDisposition, MimeType); Final alertdialog.builder downloaddialog \u003d new alertdialog.builder (MainActivity.This); downloaddialog.settitle ("download manager"); downloaddialog.setmessage ("Download this file to DonWLoad folder?" + "n" + mimeType + " n "+ URL); downloaddialog.setpositiveton (" yes ", new dialoginterface.onclicklistener () (dialogiNTERFACE, Int i) (DodownLoad (URL, FileName); dialoginterface.dismiss ();)); downloaddialog .setnegativeButton ("No", new dialoginterface.onclicklistener () (Public void onClick () () ())); downloaddialog.show ();))); ) // **************************************** // ***** ************************************ // ************ ***************************** PUBLIC VOID ConnectingTointernet () (// Receive the status of the Internet connection IsInternetPresent \u003d CD.ConnectingTointernet (); / / We check the Internet Status: if (isinternetpresent) (// Internet connection is eating // Make HTTP Requests :) Else (// Internet connections No toast.maketext (this, "Internet fell off !!!", toast.length_short) .show ( );)) @SuppressLint ("setJavascriptenable") @OVerride // Public void onresume () settings (super.onresume (); SharedPreferences SPREF \u003d PreferenceEmanager.getDefaultSharedPreferences (this); if (spref.getboolean ("img", false) ) (MWebview.getSettings (). SetloadsImagesAutomatically (false);) ELSE (MWebview.getSettings (). SetloadsImagesAutomatically (True);) if (spref.getboolean ("js", false)) (mwebview.gettings (). SetJavascriptenable false);) ELSE (MWebView.getSettings (). SetJavascriptenabled (TRUE); ) if (sprf.getboolean ("cache", false)) (cache \u003d 2;) else (cache \u003d 1;)) // Write a bookmark Public Void Savebm (String URLPAGE1, String UrLtitle1) (Intent Intent \u003d New Intent (this , Savebmactivity.class); Intent.Putextra ("UrLTITLE", URLTITLE1); INTENT.PUTEXTRA ("URLPAGE", URLPAGE1); startActivity (INTENT);) Public Void Pref () (// Intent Intens \u003d New Intent Settings (this , PreferenceSActivity.class); startActivity (Intent);) // Clean the cache and the history of Private void clcache () (Clearcache (Activity); MWebView.clearCache (TRUE); MWebView.ClearHistory (); toast.maketext (this, "cache And the story is cleared ", toast. Length_Short) .show (); ) @Override protected void onuserleavehint () (super.onuserleavehint ();) @Override Public Boolean Onkeydown (int keycode, keyEvent event) (// Button Back if ((keycode \u003d\u003d keyevent.keycode_back)) (MWebView.Cangoback () ; (MWebView.Goback ();) Return True;) Return Super.onkeydown (Keycode, Event);) // Fishing the URL of the Private Booolean Handleintent program (String Action \u003d Intent.getAction (); ifent .Action_View.equals (Action)) (String URL \u003d INTENT.GETDATASTRING (); toast.maketext (this, url, toast.length_short) .show (); MWebView.LoadURL (URL); // Georgia Return True page;) RETURN FALSE;) // Private Void Dodownload Download Manager (URIRIIGINAL \u003d URI.PARSE (URL); TRY (TOAST.MakeText (MainActivity.this, "Downloading" + FileName, toast.length_long). show (); Request Request \u003d New DownloadManager.Request (URI.PARSE (URL); Request.SetDestinationEnexternalPublicDir (Environment.directory_DownLoads, Filena me); Final DownloadManager DM \u003d (DownloadManager) GetSystemSystemVice (context.download_service); DM.Enqueue (Request); ) Catch (toast.maketext (this, "error", toast.length_short) .show (); log.e ("", "Problem downloading:" + Urioriginal, E);)) // Tyant video full screen private final WebChromeClient mWebChromeClient \u003d new WebChromeClient () (@Override @SuppressWarnings ( "deprecation") public void onShowCustomView (View view, int requestedOrientation, CustomViewCallback callback) (onShowCustomView (view, callback);) @Override public void onShowCustomView ( view view, CustomViewCallback callback) (! if (mFullScreenView \u003d null) (callback.onCustomViewHidden (); return;) mFullScreenView \u003d view; mWebView.setVisibility (View.GONE); mFullScreenContainer.setVisibility (View.VISIBLE); mFullScreenContainer.addView ( view); mFullscreenViewCallback \u003d callback;) @Override public void onHideCustomView () (super.onHideCustomView (); if (mFullScreenView \u003d\u003d null) (return;) mWebView.setVisibility (View.VISIBLE); mFullScreenView.setVisibility (View.GONE) ; mfullscreencontainer.set. Visibility (view.gone); mfulScreenContainer.RemoveView (mfullscreenview); mfullscreenviewcallback.oncustomViewhidden (); mfulScreenView \u003d NULL; ) // ********************************************* We ship files Network // OpenFileChooser for Android 3.0+ Public Void OpenFileChooser (Valuecallback uploadMsg, String acceptType) (// Message about updating mUploadMessage \u003d uploadMsg; try (// Create AndroidExampleFolder in sdcard File imageStorageDir \u003d new File (Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_PICTURES), "AndroidExampleFolder");! if (imageStorageDir.exists ( )) (// Create AndroidexampleFolder in sdcard imagestoragedir.mkdirs ();) // Create the camera captured image path to the file and the name file File \u003d New File (IMG_ "+ String.Valueof (System.CurrentTimemillis () + \u003d New Intent); i.Addcategory (INTENT.category_Openable); i.settype ("image / *"); // Create an Intent Intent Chooserintent selector select.CreateChooser (I, "Image Choos Er "); // Install Cameras intending to select Chooserintent.Putextra files (Intent.Extra_INITIAL_INENTS, New Parcelable (CaptureIntent)); // On the choice of the image bypassing the onactivityResult method Calling the StartactivityForResult activity method (Chooserintent, Filechooser_Resultcode); ) Catch (GetBaseContext (), "Exception:" + E, toast.length_long) .show ();)) // OpenFileChooser for Android< 3.0 @SuppressWarnings("unused") public void openFileChooser(ValueCallback Uploadmsg) (OpenFileChooser (Uploadmsg, ");) // @SuppressWarnings (" Unused ") Public Void OpenFileChooser (ValueCallback Uploadmsg, String AcceptType, String Capture) (OpenFileChooser (Uploadmsg, AcceptType);) Public Boolean OnConsoleMessage (OnConsoleMessage (CM.Message (), CM.LinEnumber (), cm.sourceid ()); RETURN TRUE;) Public Void OnConsoleMessage (String Message, Int LineNumber, String Sourceid) (//log.d ("androidRuntime "," Show Console Messages, Used for Debugging: "+ Message);); ); // END SETWEBCHROMECLIENT // Get the result @suppresswarnings ("Unused") Private Object Data; @Override Protected void onactivityResult (int RequestCode, Int ResultCode, Intent Data) (if (Data \u003d\u003d NULL) (Return;) String URLPage2 \u003d Data.getStringExtra ("URLPAGE2"); mwebview.loadurl (urlpage2); if (RequestCode \u003d \u003d Filechooser_resultcode) (if (null \u003d\u003d this.muploadMessage) (Return;) URI Result \u003d NULL; try (if (resultcode \u003d result_ok) (result \u003d null;) else (// Extract from its own variable if the intention consists in Zero Result \u003d Data \u003d\u003d NULL? MCAPTUREDIMAGURI: data.getdata ();)) Catch (GetApplicationContext (), "Activity:" + E, toast.length_long) .show ();) MUPLOADMESSAGE .ONReceiveValue (Result); MuploadMessage \u003d NULL;)) // ***************************** Public void Loadend () (toast .maketext (this, "file is loaded into the donwload folder", toast.length_short) .show ();) // @Override Public Boolean OnCreateOptionsmenu (Menu Menu) (// Inflate The Menu; This Adds Items To The Action Bar if IT IS PRESENT. GetMenuin Flater (). Inflate (R.Menu.main, Menu); RETURN TRUE; ) // *********************************************** ******** @OVerride Public Boolean OnoTetemSItemSelected (Item.GetItemid ()) (Case Android.r.id.home: // Home MWebView.Loadurl Button ("http: // yandex .ru "); return true; case r.id.item1: // back MWebView.CangBack (); (MWebView.goback ();) Return True; Case R.ID.Item2: // forward MWebView.cangoforward () ; (MWebView.goforward ();) Return True; Case R.ID.Item3: // Reboot MWebView.Reload (); (MWebView.Reload ();) Return True; Case R.ID.Item4: // Clee cache MWebView.clearCache (True); ClearCache (Activity); toast.maketext (this, "Cache is clean.", toast.length_short) .show (); Return True; Case R.ID.Item5: MWebView.cleArHistory (); / / Clean the history of toast.maketext (this, "Chista History.", toast.length_short) .show (); Return True; Case R.ID.Item6: Savebm (MWebview.getURL (), MWebView.gettitle ()); / / WHO Bookmark Return True; Case R.ID.Item7: // Panel Bookmarks INTENT INTENT1 \u003d NEW INTENT , Savebmactivity.class); StartatoryIFORRESULT (INTENT1, 1); RETURN TRUE; Case R.ID.Item8: // Stop loading MWebView.stoploading (); RETURN TRUE; Case R.ID.Item9: Pref (); // Settings RETURN TRUE; Case R.ID.Item10: // Still Empty Return True; Case R.ID.Item11: // IF (Cache \u003d\u003d 2) (CACHE \u003d\u003d 2) (CLCACHE ();) FINISH (); RETURN TRUE; Default: Return Super.OptionSItemSelected (Item); )) @SuppressWarnings ("Deprecation") @Override Public void onestroy () (super.ondestroy (); mwebview.stoploading (); mwebview.clearcache (true); mwebview.clearview (); MWebView.FreeMemory (); MWebview. Destroy (); MWebView \u003d NULL;) // Clash Void ClearCacheFolder (Context.GetcacheDir ();) Void ClearcacheFolder (File Dir) (If (Dir! \u003d null && dir.isdirectory ()) (Try (for (File Child: Dir.listFiles ()) (// Recursively clean it first if directories if (child.isdirectory ()) ClearCacheFolder (Child); else // then actually Child files .delete ();)) Catch (EXCEPTION E) ())))

The project can download

Android allows you to create your own window to view web pages or even create your browser clone using an item. The element itself uses the WebKit engine and has many properties and methods. We limit ourselves to a basic example of creating an application, with which we can view pages on the Internet. In the latest versions, the engine from Chromium is used, but there is no big difference in this for simple tasks.

Create a new project MyBrowser. and immediately replace the code in the markup file rES / Layout / Activity_main.xml:

Now open the activity file MainActivity.java. And we will declare the component, as well as initialize it - to include support for JavaScript and specify the page to download.

Private WebView WebView; public void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.activity_main); webView \u003d findViewById (R.id.webView); // Enables support JavaScript webView.getSettings () setJavaScriptEnabled (true). ; // Specify the WebView.Loadurl download page ("http: // Site / Android");)

Since the application will use the Internet, you need to set permission to access the Internet in the Manifest file.

There, in the manifest, we modify the line for the screen, removing the title from our application (highlighted fat):

android: Theme \u003d "@ style / theme.appompat.noactionbar">

Start the application. At our disposal, the simplest web pages view appeared, but with one disadvantage. If you click on any link, you will automatically start the default browser and the new page will be displayed already there. More precisely, it was before. On new devices, when starting the application, the browser immediately opens.

To solve this problem and open links in your program, you need to override the class WebViewClient. And allow our application to process links. Add the invested class in the code:

Private class MyWebViewClient extends WebViewClient (@TargetApi (Build.VERSION_CODES.N) @Override public boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request) (view.loadUrl (request.getUrl () toString ());. Return true;) // To old @Override Public Boolean ShoulderrideURLoading (View.Loadurl (URL); RETURN TRUE;))

Then in the method onCreate () Determine copy MyWebViewClient.. It may be anywhere after the initialization of the object:

Webview.setWebViewClient (New MyWebviewClient ());

Now in our appendix created WebViewClient.which allows you to download any specified URL selected in the container itself, and not run the browser. This functionality is responsible for the method in which we specify the current and necessary URL. Return value true. It suggests that we do not need to start a third-party browser, and independently drive the content on the link. In the version of the API 24, the overloaded version of the method has added, consider this circumstance.

Run the program and make sure that the links are downloaded now in the application itself. But now another problem arose. We cannot return to the previous page. If we click on the back button on your device, just close your application. To solve a new problem, we need to handle the button press the Back button. We add a new method:

@Override public void onbackpressed () (if (webview.cangoback ()) (WebView.goback ();) ELSE (super.onbackpressed ();))

We must check that supports navigating the previous page. If the condition is true, then the method is called goback ()which returns us to the previous page one step back. If there are several such pages, then we can consistently return to the very first page. In this case, the method will always return the value. true.. When we return to the very first page with which the journey on the Internet began, the value will be back. false And the backing button pressing the back button will already have the system itself that closes the application screen.

Run the application again. You have my own web browser, which allows you to go on the links and return to the previous page. Having studied the documentation, you can equip the application and other delicious buns for your browser.

If you need part of the links leading to your site to open in the browser, and open local links in the application, then apply a condition with different returned values.

Public Class MyWebviewClient Extends WebViewClient (@Override Public Boolean ShoulderrideurLoading (URI (URI.PARSE (URL), URI.PARSE (URL)); view.getContext (). StartActivity (INTENT); RETURN TRUE;))

Universal method that all local links will open in the application, the rest in the browser (change one line):

Public Class MyappwebViewClient Extends WebViewClient (@Override Public Boolean ShoulderrideURLoading (WebView View, String URL) ( if (URI.PARSE (URL) .Gethost (). Length () \u003d\u003d 0) (RETURN FALSE;) INTENT INTENT \u003d NEW INTENT (INTENT.Action_View, URI.PARSE (URL)); view.getContext (). Startactivity (Intent); RETURN TRUE; ))

And now a little complicate an example, so that the user has an alternative to standard browsers.

In order to be clearer, we remake an example as follows. Create two activity. In the first activity, place a button to switch to second activity, and lay the component on the second activity.

In the manifest, we prescribe a filter from the second activity.

Code for the button to transition to second activity.

Public Void OnClick ("Intent Intenscript \u003d New Intent"; Intent.SetData (URI.PARSE ("http: // Site / Android /")); startActivity (INTENT);)

We have created your own intention with the filter and provided data - the address of the site.

The second activity should take data:

Package ru.alexanderklimov.TestApplication; Import android.net.uri; Import android.Support.v7.app.appCompatactivity; Import android.os.Bundle; Import android.webkit.WebView; Import Android.webkit.WebViewClient; Public Class Secondactivity Extends AppCompatactivity (SavedInstanceState); setContentView (R.Layout.ActiveVity_second); URI URL \u003d getIntent (). GetData (); WebView WebView \u003d FindviewByid (R.ID.WebView); WebView.setWebViewClient (New Callback ()); WebView.LoadURL (URL.TOSTRING ()); ) Private Class Callback Extends WebViewClient (@Override Public Boolean ShoulderrideurLoading (Return (False);)))

In the filter for the second activity, we indicated two actions.

This means that any activity (read, applications) can cause your activity with a mini browser according to the same principle. Start in the studio in a separate window any old project or create a new one and add a button and write the same code that we used to click the button.

Run the second application (the first application can be closed) and click on the button. You will not start the first application with the initial screen, but immediately the second activity with a mini browser. Thus, any application can start the browser, not knowing the name of the class of your activity, but using only the string "ru.alexanderklimov.browser"transmitted by B. Intent. At the same time, your activity with the browser must have a default category and data. Let me remind you:

You can submit your string in the form of a string constant and inform all potential users of your browser as they can run it. But Android already has such a ready constant Action_View.which in the help of documentation is the following:

Public Static Final Java.Lang.String Action_View \u003d "Android.Intent.action.view";

I rewrite the code for the button for the second application

INTENT (Android.Content.Intent.action_View, uri.parse ("http: // Site / Android /")); StartActivity (INTENT);

What will happen this time? We remember that we have two actions, including android.Intent.action.view.. So, our first application with the browser should also recognize this command when a user uses this code. On the emulator at least there is one such program "Browser", and now our second activity from the first application has been added to it. A selection of two applications will appear on the screen.

And if you delete all alternative browsers and leave only your program, then there will be no choice. Your browser will be the main one. And if some application wants to start the web page in the specified way, your program will open.

Small remark. If you replace the last line to such:

StartActivity (Intent.createChooser (Intent, "Meow ..."));

In the program selection window, instead of the top line "Open WITH" or its local translation will appear your row. But this is not the main thing. If for some reason there will be no browser on the device, then this code option will not cause the collapse of the application, unlike the initial option. Therefore, use the proposed option for the sake of reliability.

Let's create a new application - browser for Android devices, with your own hands, it will be interesting, and the code will not have a lot.

Android browser application

Start Android Studio and create a new project, Application Name My Site, Company Domain at your discretion, I entered the site domain site. We click Next, on the next tab, leave everything without changing, click Next, then already selected Empty Activity, I will leave it, then in the last tab I will change the Layout Name with Activity_Main on Main, and press the finish.

Android Studio. Prepare project files, it will take some time. The main window will open two files, main.xml. and MainActivity.java.Let's start working in the latter. Change Extended AppCompactactivity on Activity, keep.

Adding permits to manifest

Then open the file Androidmanifest.xml. and add user permission after the first section user-permission,

what would our application have access to the Internet. Save and close AndroidManifest.xml.

Go to file. Main.xml., It is on the way RES / layout / main.xml, delete the Android string: text \u003d "Hello Word!" Fully, change the textView on WebView, from the properties of the main layer RelativeLayout remove unnecessary indents (PaddingBottom, Paddingleft, PaddingRight, PaddingTop).

For WebView add the Android property: id \u003d "@ + id / webview", change Android: layout_width \u003d "wrap_content" and Android: layout_height \u003d "wrap_content" on Android: layout_width \u003d "match_parent" and Android: layout_height \u003d "match_parent" for What our element WebView was on the entire screen.

Codes logic on java

With the main.xml file, we finished, moving to MainActivity.java.. Add a variable wV. Type WebView.We assign it an element by finding it using the FindViewByid () function, we describe the WV settings, in particular, allowing Java scripts to WebView, specify the site download address to our browser, I will run Yandex, applying the Loadurl function ("http: // ya.ru ").

public class MainActivity extends Activity (WebView wv; @Override protected void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); wv \u003d (WebView) findViewById (R.id.webView); WebSettings Settings \u003d WV.getSettings (); settings.setjavascriptenabled (true); WV..SetWebViewClient (new webviewClient ());)

Also below we write the handling of the press button back on the device.

@Override public void onbackpressed () (if (wv.cangoback ()) (wv.goback ();) else (super.onbackpressed ();))

Run an application in the emulator

Press the START button, this is a green triangle on the toolbar AndroidStudio.Our emulator will start, and if everything is done correctly, after some time the Yandex search will start in the browser, you can put on a virtual keyboard and search for something, everything works well.

Close the program without closing the emulator yourself by clicking on the red rectangle, it is Stop instead of START, change the address to arbitrary, I "propiaria" my site "https: // Site",

click Save and re-run the program, this time everything will happen faster, getting around the site, in the programming section for Android there are articles and videos how to install and configure AndroidStudio, make an Android emulator and simple examples of programs.

Full text androidmanifest.xml

Full text Main.xml.

Full text MainActivity.java.

package RU.MaxFad.Mysite; Import Android.app.ActiveIVITY; Import android.os.Bundle; Import Android.Webkit.WebSettings; Import android.webkit.WebView; Import Android.webkit.WebViewClient; public class MainActivity extends Activity (WebView wv; @Override protected void onCreate (Bundle savedInstanceState) (super.onCreate (savedInstanceState); setContentView (R.layout.main); wv \u003d (WebView) findViewById (R.id.webView); WebSettings Settings \u003d WV.getSettings (); settings.setjavascriptenabled (true); WV..SetWebViewClient (New WebViewClient ());) @Override public void onbackpressed () (if (wv.cangoback ()) (WV.Goback (); ) ELSE (super.onbackpressed ();)))

In this video, it is shown in detail how to create a browser application for Android devices:

We have already begun fully secure yourself with personal software, remember our wonderful calculator and converter. And in this lesson, we will learn how to create a simple browser, with the help of which will push the Internet spaces. Agree, surf the network on your own browser - this is more pleasant than doing this to Opera or Chrome (hardly more convenient, but more pleasant :)). Create a new project, the names traditionally choose themselves. Personally, I generally do not create everything from scratch every time, but I just open what is, and I cleaned the entire code to the original state of the Blank Activity. Do how more convenient to you.

So, briefly outline the volume and specifics of follow-up. We need to create an item in which it will happen to write a code that creates our personal web browser, to equip it with basic functions, prescribe permission to use the Internet by our application in the manifest file, and write a hardware button handler "Back" On the device (that is, what will happen in our browser when you click on this button).

Let's start. Open the file activity_Main.xml.. Create there one single element there We are enough for us to implement a web browser:

< WebView xmlns: android= "http://schemas.android.com/apk/res/android" Android: layout_height \u003d "Match_Parent" Android: layout_width \u003d "match_parent" android: id \u003d "@ + id / web" /\u003e

The markup window will look like this:

After that, let's immediately understand the file Androidmanifest.xml.. We open it and add two lines there, one is permission for the application to use the Internet, the other is to change the style of the application, and more precisely hiding the "title" panel of the application (panels with the application header) with the goal to provide the browser window more space to display pages .

We write a string of permission to use the Internet before Opening tag ...:

< uses- permission android: name= "android.permission.INTERNET" / >

Now add to the row setting our Activitycommand to hide the title (Lower line highlighted in fat, it is also located in Androidmanifest.xml.):

< activity android: name= ".MainActivity" android: label= android: Theme \u003d "@android: style / theme.notitlebar" >

Now go to the most important and responsible part of the work - writing a Java code. Open the MainActivity.java file and write the following (explanations are given in the code after signs //, who did not notice):

package Home.Myapplication; Import Android.app.ActiveIVITY; Import Android.app.Alertdialog; Import android.content.contentvalues; Import android.Content.intent; Import android.database.cursor; Import android.database.sqlite.sqliteDatabase.; Import android.database.sqlite.sqliteOpenHelper.; Import android.Support.v7.app.actionBaractivity; Import android.os.Bundle; Import android.util.log; Import Android.View.KEYEVENT; Import android.view.Menu; Import Android.view.MenuItem; Import Android.View.View; Import android.webkit.WebView; Import Android.webkit.WebViewClient; Import android.widget.button; Import Android.widget.EditText; Import android.widget.RadioButton; Import android.widget.textView; Public Class MainActive Extends Activity ( // declare a variable type WebView Private WebView MWeb; // Create a class of type web browser (WebViewClient), which is configured // Default Permission to process all links within this class, // Without referring to third-party programs: private class WebViewer extends WebViewClient ((WebView view, String url) (view loadUrl (url);. return true;)) public void onCreate (Bundle savedInstanceState) (super onCreate (savedInstanceState);. setContentView (R layout activity_main)..; // tie the announced variable of type WebView to the created by us // WEBVIEW item in the Activity_Main.xml file: MWeb \u003d (WebView) FindViewByid (R. ID. Web); // We connect Java scripts to this item: MWEB. GetSettings (). SetJavascriptenabled (TRUE); // Configure the page that will download when startup, you can enter any: MWEB. Loadurl ( "http://developeroleg.ucoz.ru/"); // Customize the browser for our WebView element, we connect the above // Web client with which the pages will be viewed: MWEB. SetWebViewClient (New WebViewer ()); ) // We write the processing code for pressing the back button on the device, which will allow us when you click // On the "Back" button, go to the previous page, and not just close the applications. // it will close the "Back" button only if we are on the starting // Page, which indicated above: @Override public void onbackpressed () (if (MWeb. Cangoback ()) (MWeb. Goback ();) ELSE (Super. Onbackpressed ();)))

That's all! In fact, everything is quite simple and after short works we have our own browser, of course, it is quite simple and has no options, but to understand the essence of the creation of such applications, this is quite enough.