Wednesday 17 August 2016

WebView


Webview

Google
Webview is used to display online and offline web content to android device. Online content means we are accessing web content from internet only. We can also specify HTML string and can show it inside our application using a WebView. Basically, WebView turns application into a web application.















Permission
In order to access online web content, You must need Internet permission. Declare this permission in your  android manifest file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   
package="sichlearning.example.com.testone">

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

    <
application
       
android:allowBackup="true"
       
android:icon="@mipmap/ic_launcher"
       
android:label="@string/app_name"
       
android:supportsRtl="true"
       
android:theme="@style/AppTheme">
        <
activity android:name=".MainActivity">
            <
intent-filter>
                <
action android:name="android.intent.action.MAIN" />

                <
category android:name="android.intent.category.LAUNCHER" />
            </
intent-filter>
        </
activity>
    </
application>

</
manifest>

Add webView to application
Whole Web Activity
You can convert your whole activity to web layout but you are unable to add anyother functionality in this.
Like this -
<?xml version="1.0" encoding="utf-8"?>

<WebView  xmlns:android="http://schemas.android.com/apk/res/android"

    android:id="@+id/webview"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    />

Webview to layout with functionality
·         Add webview to inside another layout with appropriate height and width
·         Now, You are able to add some functionality in this.
Code -
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

<Button

    android:id="@+id/btn1"

    android:layout_width="wrap_content"

    android:layout_height="wrap_content" />

    <WebView

        android:id="@+id/webView1"

        android:layout_width="match_parent"

        android:layout_height="match_parent"></WebView>

</LinearLayout>


Accessing the WebView From Code
Once you have inserted a WebView into a layout somewhere, you can access it from your code. You need to access the WebView to make it do anything interesting.
**********************************************************
public class MainActivity extends Activity {



    WebView webView1;



    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        webView1=(WebView)findViewById(R.id.webView1);

        button1=(Button)findViewById(R.id.btn1);



    }

}
*****************************************************************************
Loading a URL to Webview
To load the website in the webview, we use loadURL() method.
public class MainActivity extends Activity {



    WebView webView1;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

       

        webView1=(WebView)findViewById(R.id.webView1);

       webView1.loadUrl("http://www.google.com");

        

    }

}

Note :   It's not open the website inside webview and refer toanother available in your phone.
Enable javascript in Webview
You can retrieve WebSettings with getSettings(), then enable JavaScript with setJavaScriptEnabled().
code -
public class MainActivity extends Activity {



    WebView webView1;

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        webView1=(WebView)findViewById(R.id.webView1);

        WebSettings webSettings = webView1.getSettings();

        webSettings.setJavaScriptEnabled(true);

       webView1.loadUrl("http://www.google.com");



    }

}

Open in Webview
To keep page navigation within the WebView and hence within your app, you need to create a subclass of WebViewClient, and override its shouldOverrideUrlLoading(WebView webView, String url) method. Here is how such a WebViewClient subclass could look:
private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        return false;
    }
}
When the shouldOverrideUrlLoading() method returns false, the URLs passed as parameter to the method is loaded inside the WebView instead of the Android standard browser. In the above example all URls will be loaded inside the WebView.
If you want to distinguish between that URLs are loaded inside the WebView and which are loaded in the Android browser, your implementation of shouldOverrideUrlLoading() can examine the URL passed to it as parameter. Here is an example that only loads URLs that contains jenkov.com inside the WebView and all other URLs in the Android browser:
public class WebViewClientImpl extends WebViewClient {
 
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        if(url.indexOf("jenkov.com") > -1 ) return false;
        return true;
    }
 
}
Weirdly enough, returning true from shouldOverrideUrlLoading() does not cause the URL to be loaded in the external Android browser. Rather, it causes the URL not to be loaded at all. To open all other URLs in the external Android browser you will have to fire an Intent. Here is how the WebViewClient subclass looks with that added:
 public class WebViewClientImpl extends WebViewClient {
 
    private Activity activity = null;
 
    public WebViewClientImpl(Activity activity) {
        this.activity = activity;
    }
 
    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        if(url.indexOf("jenkov.com") > -1 ) return false;
 
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        activity.startActivity(intent);
        return true;
    }
 
}
Notice how the WebViewClientImpl class now takes an Activity in its constructor. This activity is used to fire the Intent which opens the URL in the Android browser.
************************************************************************
XML
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <WebView

        android:id="@+id/webView1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"></WebView>

</LinearLayout>

Java
public class MainActivity extends Activity {



    WebView webView1;



    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        webView1 = (WebView) findViewById(R.id.webView1);



        webView1.setWebViewClient(new MyWebViewClient());

        openURL();

    }



    /** Opens the URL in a browser */

    private void openURL() {

        webView1.loadUrl("http://www.google.com");

        webView1.requestFocus();

    }

    private class MyWebViewClient extends WebViewClient {

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);

            return true;

        }

    }

}
********************************************************************************

Binding JavaScript code to Android code



activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <WebView

        android:id="@+id/webView1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"></WebView>

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {



    WebView webView1;



    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        webView1 = (WebView) findViewById(R.id.webView1);

        webView1.loadUrl("file:///android_asset/web.html");



        webView1.getSettings().setJavaScriptEnabled(true);

        webView1.addJavascriptInterface(new WebViewJavaScriptInterface(this), "app");

    }



    /*

     * JavaScript Interface. Web code can access methods in here

     * (as long as they have the @JavascriptInterface annotation)

     */

    public class WebViewJavaScriptInterface{



        private Context context;



        /*

         * Need a reference to the context in order to sent a post message

         */

        public WebViewJavaScriptInterface(Context context){

            this.context = context;

        }



        /*

         * This method can be called from Android. @JavascriptInterface

         * required after SDK version 17.

         */

        @JavascriptInterface

        public void makeToast(String message, boolean lengthLong){

            Toast.makeText(context, message, (lengthLong ? Toast.LENGTH_LONG : Toast.LENGTH_SHORT)).show();

        }

    }



}

Create Assets Folder - Right click on 'app'->Go to folder->Assets Folder->OK
Now, Paste this code in folder.
Name it : web.html
<!DOCTYPE html>

<html>

<head>

    <title>JavaScript View</title>



    <script type="text/javascript">



        function showToast(){

            var message = document.getElementById("message").value;

            var lengthLong = document.getElementById("length").checked;



            /* 

                Call the 'makeToast' method in the Java code. 

                'app' is specified in MainActivity.java when 

                adding the JavaScript interface. 

             */

            app.makeToast(message, lengthLong);

            return false;

        }



        /* 

            Call the 'showToast' method when the form gets 

            submitted (by pressing button or return key on keyboard). 

         */

        window.onload = function(){

            var form = document.getElementById("form");

            form.onsubmit = showToast;

        }

    </script>

</head>



<body>



<form id="form">

    Message: <input id="message" name="message" type="text"/><br />

    Long: <input id="length" name="length" type="checkbox" /><br />



    <input type="submit" value="Make Toast" />

</form>



</body>

</html>
Calling From Android Web App to JavaScript
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent"

    >

    <TextView

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="@string/hello"

        />

    <EditText

        android:id="@+id/msg"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content" />

    <Button

        android:id="@+id/sendmsg"

        android:layout_width="fill_parent"

        android:layout_height="wrap_content"

        android:text="Msg to JavaScript"

        />

    <WebView

        android:id="@+id/mybrowser"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent"

        />

</LinearLayout>

MainActivity.java
public class MainActivity extends Activity {



    WebView myBrowser;

    EditText Msg;

    Button btnSendMsg;



    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        myBrowser = (WebView)findViewById(R.id.mybrowser);



        final MyJavaScriptInterface myJavaScriptInterface

                = new MyJavaScriptInterface(this);

        myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");

        myBrowser.getSettings().setJavaScriptEnabled(true);



        myBrowser.loadUrl("file:///android_asset/web.html");



        Msg = (EditText)findViewById(R.id.msg);

        btnSendMsg = (Button)findViewById(R.id.sendmsg);

        btnSendMsg.setOnClickListener(new Button.OnClickListener(){



            @Override

            public void onClick(View arg0) {

                // TODO Auto-generated method stub

                String msgToSend = Msg.getText().toString();

                myBrowser.loadUrl("javascript:callFromActivity(\""+msgToSend+"\")");



            }});



    }



    public class MyJavaScriptInterface {

        Context mContext;



        MyJavaScriptInterface(Context c) {

            mContext = c;

        }



        public void showToast(String toast){

            Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();

        }



        public void openAndroidDialog(){

            AlertDialog.Builder myDialog

                    = new AlertDialog.Builder(MainActivity.this);

            myDialog.setTitle("DANGER!");

            myDialog.setMessage("You can do what you want!");

            myDialog.setPositiveButton("ON", null);

            myDialog.show();

        }



    }

}

Create Assets Folder - Right click on 'app'->Go to folder->Assets Folder->OK
Now, Paste this code in folder.
Name it : web.html
<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <meta name="viewport" content="width=device-width; user-scalable=0;" />

    <title>My HTML</title>

</head>

<body>

<h1>MyHTML</h1>

<p id="mytext">Hello!</p>

<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />

<input type="button" value="Open Dialog" onClick="openAndroidDialog()" />

<script language="javascript">

   function showAndroidToast(toast) {

       AndroidFunction.showToast(toast);

   }



   function openAndroidDialog() {

       AndroidFunction.openAndroidDialog();

   }



   function callFromActivity(msg){

 document.getElementById("mytext").innerHTML = msg;

   }

</script>



</body>

</html>
*****************************************************************************
4. goBack() – Move to one page back if a back history exist
Code -
public void goBack(View view)

{

    if ( webView1.canGoBack()) {

        // checks whether a web view has a back history item or not

        webView1.goBack();

    }

}

5. goForward() – Move one page forward if forward history exist
public void goNext(View view)

{

    if ( webView1.canGoForward()) {

        // checks whether a web view has a forward history item or not

        webView1.goForward();

    }

}
 6. Go to one step back, when press phone back button
@Override

public boolean onKeyDown(int keyCode, KeyEvent event)

{

    if ((keyCode == KeyEvent.KEYCODE_BACK) && webView1.canGoBack()) {

        webView1.goBack();

        return true;

    }

    return super.onKeyDown(keyCode, event);

}

Downloading all type file
Permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

Code -
//   download

        webView1.setDownloadListener(new DownloadListener() {



            public void onDownloadStart(String url, String userAgent,

                                        String contentDisposition, String mimetype,

                                        long contentLength) {

                DownloadManager.Request request = new DownloadManager.Request(

                        Uri.parse(url));



                request.allowScanningByMediaScanner();

                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!

                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Download");

                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

                dm.enqueue(request);

                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!

                intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE

                intent.setType("*/*");//any application,any extension

                Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded

                        Toast.LENGTH_LONG).show();



            }

        });

============================================================================
                                                                Browser
============================================================================
manifest.xml
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="sichlearning.example.com.browse">



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

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



    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:supportsRtl="true"

        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />



                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>



</manifest>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

    android:orientation="vertical" android:layout_width="match_parent"

    android:layout_height="match_parent">

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:background="#f5f5f5"

        >

        <EditText

            android:id="@+id/et_web"

            android:layout_width="0dp"

            android:layout_height="wrap_content"

            android:layout_weight="1"

            />

        <Button

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Go"

            android:onClick="goweb"

            />

    </LinearLayout>

    <LinearLayout

        android:layout_width="match_parent"

        android:layout_height="wrap_content"

        android:orientation="horizontal"

        android:background="#f5f5f5"

        >

        <Button

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Back"

            android:textSize="25dp"

            android:onClick="goBack"

            />



        <Button

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="Next"

            android:textSize="25dp"

            android:onClick="goNext"

            />

        <Button

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:text="H"

            android:textSize="25dp"

            android:onClick="goHistory"

            />

      

    </LinearLayout>

    <WebView

        android:id="@+id/webView1"

        android:layout_width="fill_parent"

        android:layout_height="fill_parent">

    </WebView>



</LinearLayout>

mainActivity.java
public class MainActivity extends Activity {



    WebView webView1;

    EditText editText1;

    boolean clearHistory = false;



    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);



        editText1=(EditText)findViewById(R.id.et_web);

        webView1 = (WebView) findViewById(R.id.webView1);



        webView1.setWebViewClient(new MyWebViewClient());



//   download

        webView1.setDownloadListener(new DownloadListener() {



            public void onDownloadStart(String url, String userAgent,

                                        String contentDisposition, String mimetype,

                                        long contentLength) {

                DownloadManager.Request request = new DownloadManager.Request(

                        Uri.parse(url));



                request.allowScanningByMediaScanner();

                request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED); //Notify client once download is completed!

                request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "Download");

                DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

                dm.enqueue(request);

                Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); //This is important!

                intent.addCategory(Intent.CATEGORY_OPENABLE); //CATEGORY.OPENABLE

                intent.setType("*/*");//any application,any extension

                Toast.makeText(getApplicationContext(), "Downloading File", //To notify the Client that the file is being downloaded

                        Toast.LENGTH_LONG).show();



            }

        });



    }



    public void goweb(View view)

    {

        String raw_url=editText1.getText().toString();

        String url="http://"+raw_url;

        if(url.endsWith(".com"))

        {    openURL(url);  }

        else

        {

            String url1="https://www.google.co.in/search?site=&source=hp&q="+raw_url;

            openURL(url1);

        }

    }

    /** Opens the URL in a browser */

    private void openURL(String web) {

        webView1.loadUrl(web);

        webView1.requestFocus();

    }

    private class MyWebViewClient extends WebViewClient {

        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);

            return true;

        }

    }

    public void goBack(View view)

    {

        if ( webView1.canGoBack()) {

            // checks whether a web view has a back history item or not

            webView1.goBack();

        }

    }

    public void goNext(View view)

    {

        if ( webView1.canGoForward()) {

            // checks whether a web view has a forward history item or not

            webView1.goForward();

        }

    }

    public void goHistory(View view)

    {

        WebBackForwardList history = webView1.copyBackForwardList();

        int index = -1;

        String url = null;

        url = history.getItemAtIndex(history.getCurrentIndex()).getUrl();

        editText1.append(url);

    }







    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event)

    {

        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView1.canGoBack()) {

            webView1.goBack();

            return true;

        }

        return super.onKeyDown(keyCode, event);

    }



}


































22

No comments:

Post a Comment