An advanced WebView with some cool features

I was angry with the official Facebook app for Android. It’s really heavy and I don’t mean the size of the package which is not actually a problem. The problem is that Facebook Mobile uses a lot of RAM and battery drain is not acceptable for me. That’s why I always prefered to use a mobile website rather than the official app.

When I started getting to know Android programming I decided to create an app which could help people using Facebook website. I wanted to have some cool Android features like pull to refresh and drawer layout. I did some research and found something needed to create a Web App. WebView allows you to use Android browser (Chromium) inside your app. It can support Java Script and it has actually all the features present in Google Chrome. So how to implement a simple WebView in you app? How to build something more advanced? I’m gonna show you right now.

First add INTERNET permission to your Manifest and add WebView to your layout xml file.

<uses-permission android:name="android.permission.INTERNET" />
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Now short piece of code to your Activity.

private WebView webView;

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

        webView = (WebView) findViewById(R.id.webView1);
        webView.loadUrl("http://m.facebook.com");
        webView.setWebViewClient(new MyAppWebViewClient());
    }

    // handling back button
    @Override
    public void onBackPressed() {
        if(webView.canGoBack()) {
            webView.goBack();
        } else {
            super.onBackPressed();
        }
    }

As you noticed I used a new WebView Client to have a possibility to customize the WebView.

package org.indywidualni.myapplication;

import android.content.Intent;
import android.net.Uri;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MyAppWebViewClient extends WebViewClient {

    // handling external links as intents
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {

        if( Uri.parse(url).getHost().endsWith("facebook.com") ) {
            return false;
        }

        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    }

}

As a result I achieved a simple implementation of a WebView. But it’s not enough to have for example file upload support (including a possibility to take pictures with your camera) while using online and local forms. And what about Java Script support and error handling? A Progress Bar would be also nice. I spent some time looking for all the solutions implemented below but it is worth the result.

Continue reading An advanced WebView with some cool features