Android WebView Example

Android WebView is an extension of the View class that helps display web content. You can have the web view take the complete layout or just a portion of the screen. Say for example you want to print an Address and then display it using Google Maps inside a WebView. It doesn’t support all features of a regular browser but you can enable Javascript inside your Web View and also override the Back button to view if there are any history pages. With the help of the JavaScriptInterface you can use JavaScript to call functions inside the Activity. That way you can use the Alert Builder to display alerts instead of plain Javascript alert function and much more. Also you can choose to open links in the same WebView or not, by default all links will open in the default browser window.

Please note: In order for your Activity to access the Internet and load web pages in a WebView, you must add the INTERNET permissions to your Android Manifest file

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

How to load a Web page using an URL

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

How to load data from an HTML String

1
2
String myHtml = "<html><body>A very basic <b>WebView</b> demo!</body></html>";
webview.loadData(myHtml, "text/html", null);
Android WebView Example
Android WebView Alert Example

Android Manifest

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?xml version="1.0" encoding="utf-8"?>
    package="com.as400samplecode"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="15" />
 <uses-permission android:name="android.permission.INTERNET" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.Holo.Light">>
        <activity
            android:name=".AndroidWebViewActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

 

Android Layout

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?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" >
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="10dp"
        android:text="@string/hello"
        android:textSize="20sp" />
    <WebView
        android:id="@+id/webView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

 

Android Activity

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package com.as400samplecode;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class AndroidWebViewActivity extends Activity {
    
 private WebView myWebView;
 private String LOG_TAG = "AndroidWebViewActivity";
 
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        myWebView = (WebView) findViewById(R.id.webView1);
        
        //enable Javascript
        myWebView.getSettings().setJavaScriptEnabled(true);
        
        //loads the WebView completely zoomed out
        myWebView.getSettings().setLoadWithOverviewMode(true);
        
        //true makes the Webview have a normal viewport such as a normal desktop browser
        //when false the webview will have a viewport constrained to it's own dimensions
        myWebView.getSettings().setUseWideViewPort(true);
        
        //override the web client to open all links in the same webview
        myWebView.setWebViewClient(new MyWebViewClient());
        myWebView.setWebChromeClient(new MyWebChromeClient());
        
        //Injects the supplied Java object into this WebView. The object is injected into the
        //JavaScript context of the main frame, using the supplied name. This allows the
        //Java object's public methods to be accessed from JavaScript.
        myWebView.addJavascriptInterface(new JavaScriptInterface(this), "Android");
        
        //load the home page URL
 
    }
 
 //customize your web view client to open links from your own site in the
 //same web view otherwise just open the default browser activity with the URL
 private class MyWebViewClient extends WebViewClient {
     @Override
     public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (Uri.parse(url).getHost().equals("demo.mysamplecode.com")) {
             return false;
         }
         Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
         startActivity(intent);
         return true;
     }
 }
 
 private class MyWebChromeClient extends WebChromeClient {
     
  //display alert message in Web View
  @Override
     public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
         Log.d(LOG_TAG, message);
         new AlertDialog.Builder(view.getContext())
          .setMessage(message).setCancelable(true).show();
         result.confirm();
         return true;
     }
 }
 
 public class JavaScriptInterface {
     Context mContext;
     // Instantiate the interface and set the context
     JavaScriptInterface(Context c) {
         mContext = c;
     }
     
     //using Javascript to call the finish activity
     public void closeMyActivity() {
         finish();
     }
     
 }
 
 //Web view has record of all pages visited so you can go back and forth
 //just override the back button to go back in history if there is page
 //available for display
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
     if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack()) {
         myWebView.goBack();
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }
 

Run, Install , Debug Android Application thông qua Wifi

Sau đây mình sẽ hướng dẫn các bạn cách chạy, cài đặt, debug, … nói chung là lập trình Android thông qua wifi, không cần dây dợ lằng nhằng nữa.

A. Điều kiện.

1. Đầu tiên, điện thoại của bạn phải đã bật chức năng “USB debugging”, nói chung là đã có thể lập trình thông qua cáp USB.

2. Đã kết nối với máy tính thông qua wifi. (các bạn có thể dùng phần mềm Connectify để phát wifi từ máy tính, còn cách tạo mạng ad-hoc có sẵn trong Windows 7 thì mình chưa thử).

3. Biết được địa chỉ IP của điện thoại. Để biết được địa chỉ IP của điện thoại các bạn làm như sau:
Setting –> System –> kéo xuống dưới cùng chọn “About phone” –> chọn Status –> kéo xuống dưới, các bạn sẽ thấy dòng IP address, nó đó, nhớ nó để tý còn dùng, như của mình là192.168.12.184. Còn đây là hình minh họa.

get IP.JPG
B. Cách làm:

1. Mở CMD trỏ đến thư mục “platform-tools” trong thư mục “sdk”. Để cho nhanh mình có 1 mẹo như sau. Bạn mở đến thư mục “sdk”, chọn thư mục “platform-tools”, giữ phím SHIFT, đồng thời bấm chuột phải, trong menu hiện ra, bấm vào dòng “open command window here”.

open CMD.JPG

2. Kết nối:
Trong màn hình CMD, các bạn lần lượt gõ các lệnh sau và bấm enter:

PHP:
adb tcpip 5555
adb connect 192.168.12.184
debug over wifi.JPG

Trong đó bạn hãy thay 192.168.12.184 bằng địa chỉ IP của điện thoại của bạn mà bạn lấy được ở phần A.
Bây giờ các bạn có thể rút cáp USB ra và vẫn chạy được chương trình bình thường từ Eclipse.

3. Quay lại chế độ USB.

Nếu bạn không muốn lập trình thông qua wifi nữa, mà muốn quay lại chế độ lập trình thông qua cáp USB thì các bạn làm như sau.

– Cắm cáp USB lại.
– Gõ lệnh

PHP:
adb usb

và bấm Enter.

swicth to USB mode.JPG

Chúc các bạn thành công.