This lesson:
- code simple browser

 

Last lesson we saw that, browser would be displayed with http link content if we launch intent with action = ACTION_VIEW and data = Uri object with http link. We can code simple browser by ourself. It will catch such an intent and display a web page. To do this, we will adjust Intent Filter and use WebView component.

The first layout will contain an intent launching button, and the second will contain a WebView.

Let’s create a project:

Project name: P0321_SimpleBrowser
Build Target: Android 2.3.3
Application name: SimpleBrowser
Package name: ru.startandroid.develop.p0321simplebrowser
Create Activity: MainActivity

 

Code main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
        <Button
            android:id="@+id/btnWeb"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="web">
        </Button>
</LinearLayout>

There is just one button on the screen

 

Let's code MainActivity.java:

package ru.startandroid.develop.p0321simplebrowser;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

public class MainActivity extends Activity {
  /** Called when the activity is first created. */
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    (findViewById(R.id.btnWeb)).setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.ya.ru")));
      }
    });
  }
}

The code is a little bit uncommon. Note, I don’t determine the Button object. findViewById method returns a View object supporting the setOnClickListener method which I call. Within the setOnClickListener method, I create an object which implements a OnClickListener interface, and code within onClick method. I also create an Intent not separately but within startActivity. Such an option may suits you.

So, we launch an intent, which means that we want to load http://www.ya.ru, by clicking the button.

 

Let’s create the second activity. At first, we code browser.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
        <WebView
            android:id="@+id/webView"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        </WebView>
</LinearLayout>

 

There is a WebView on the screen.

 

Let's code BrowserActivity.java:

package ru.startandroid.develop.p0321simplebrowser;

import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;

public class BrowserActivity extends Activity {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.browser);

    WebView webView = (WebView) findViewById(R.id.webView);
    webView.setWebViewClient(new WebViewClient());
    Uri data = getIntent().getData();
    webView.loadUrl(data.toString());
  }
}

Find WebView, extract data from Intent and pass the String to WebView.

 

Now let’s register Activity within the manifest and add an Intent Filter action = ACTION_VIEW. We see several parameters for data. We will use Scheme = http.

That means the Uri object must content an http-address.

Don’t forget about Category which must be equal to Default and set the Label parameter for BrowserActivity with MyBrowser, for example.

You also must add Uses Permission  android.permission.INTERNET within Permissions tab, this will allow the app to connect to internet.

 

Now we save and launch our app. We will see a choice-dialog after clicking the button: system suggests us to choose between system browser and ours one, which we have just made. It means that Intent with http view request has found two activities, which declared within their IntentFilters they can display http links 

 

 

We choose our browser and see the web page

Now we see, that activities in our apps can process not only our actions, but also system ones. This is the way they become alternative to system apps.

As you see, we easily could not use WebView in our Activity and don’t show a web-page content. We could use TextView and display just only a string value of the link, we got from data. Or we could code an http-request, which will download the webpage, and display its html content. We could just give a damn about http address and show any random picture or just a dark screen.

I.e. this way Intent Filter is telling system, that activity, able to do something, could be created, but the same time activity may display something rubbish. It’s a question of ethics, adequacy and a common sense.

 

Manifest code:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="ru.startandroid.develop.p0321simplebrowser" android:versionCode="1" android:versionName="1.0">
        <uses-sdk android:minSdkVersion="10"></uses-sdk>
        <uses-permission android:name="android.permission.INTERNET"></uses-permission>
        <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
                <activity android:label="@string/app_name" android:name=".MainActivity">
                        <intent-filter>
                                <action android:name="android.intent.action.MAIN"></action>
                                <category android:name="android.intent.category.LAUNCHER"></category>
                        </intent-filter>
                </activity>
                <activity android:label="MyBrowser" android:name="BrowserActivity">
                        <intent-filter>
                                <action android:name="android.intent.action.VIEW"></action>
                                <data android:scheme="http"></data>
                                <category android:name="android.intent.category.DEFAULT"></category>
                        </intent-filter>
                </activity>
        </application>
</manifest>

 

Next lesson:

- save data with Preferences.


Присоединяйтесь к нам в Telegram:

- в канале StartAndroid публикуются ссылки на новые статьи с сайта startandroid.ru и интересные материалы с хабра, medium.com и т.п.

- в чатах решаем возникающие вопросы и проблемы по различным темам: Android, Compose, Kotlin, RxJava, Dagger, Тестирование, Performance 

- ну и если просто хочется поговорить с коллегами по разработке, то есть чат Флудильня




Language