Lập trình Android tiếng Việt - Chapter 10: Android The WebKit Browser
Với Android, ta có thể nhúng trình duyệt web có sẵn dưới dạng một widget vào trong các activity để hiển thị các nội dung HTML hoặc để duyệt Internet.
Android browser dựa trên WebKit, engine được dùng cho trình duyệt Safari Web của Apple.
Android dùng widget WebView để làm chỗ trú cho các trang của trình duyệt
Ứng dụng dùng WebView phải yêu cầu INTERNET permission.
bView2: Passing Objects between Android and JS Putting the pieces together: Place a WebView in the main.xml file Place html page in the assets folder Create the Java object to share with JS Warning: tested on Android 2.2 18 10. Android – UI – The WebKit Browser WebKit Browser 18 Part1. WebView2: Passing Objects between Android and JS Android_Passing_HTML_JS function whereami() { // html asks android to provide data using object's GET methods document.getElementById("lat").innerHTML=locater.getLatitude(); document.getElementById("lon").innerHTML=locater.getLongitude(); document.getElementById("myText").value = locater.getCommonData(); } function talkBack2Android() { // bridge object used to send local (html) data to android app locater.setCommonData("Greetings from html"); var spyHtml = "Spy data coming from HTML\n" + "\n" + document.getElementById("myText").value + "\n" + document.getElementById("lat").innerHTML + "\n" + document.getElementById("lon").innerHTML; locater.htmlPassing2Android(spyHtml); } You are at Latitude (unknown) Longitude (unknown) Click to Get Location Enter some data here 19 10. Android – UI – The WebKit Browser WebKit Browser 19 Part1. WebView2: Passing Objects between Android and JS public class Main extends Activity { private WebView browser; MyLocater locater = new MyLocater(); Location mostRecentLocation; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); // get a location fix (lat, lon) mostRecentLocation = fakeGetLocation(); // set up the webview to show location results browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.addJavascriptInterface(locater, "locater"); browser.loadUrl("file:///android_asset/my_local_page1.html"); } private Location fakeGetLocation() { // faking the obtaining of a location object (discussed later!) Location fake = new Location("fake"); fake.setLatitude(9.938038); fake.setLongitude(-84.054430); return fake; } 20 10. Android – UI – The WebKit Browser WebKit Browser 20 Part1. WebView2: Passing Objects between Android and JS // "MyLocater" dùng để gửi dữ liệu qua lại giữa Android và mã JS public class MyLocater { private String commonData = "XYZ"; public double getLatitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLatitude(); } public double getLongitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLongitude(); } public void htmlPassing2Android(String dataFromHtml) { Toast.makeText(getApplicationContext(), "1\n" + commonData, 1).show(); commonData = dataFromHtml; Toast.makeText(getApplicationContext(), "2\n" + commonData, 1).show(); } public String getCommonData(){ return commonData; } public void setCommonData(String actualData){ commonData = actualData; } }//MyLocater } 21 10. Android – UI – The WebKit Browser WebKit Browser 21 Part2. WebView3: Using Google Maps V3 Webpage “webview_map.html” showing a Google map centered around Cleveland State University, Ohio (seen with IExplorer running in a Windows machine) Link: html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } function initialize() { var latlng = new google.maps.LatLng(41.5020952, -81.6789717); var myOptions = { zoom: 15, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP }; var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); } 22 10. Android – UI – The WebKit Browser WebKit Browser 22 Part2. WebView3: Passing Objects between Android and JS This is the web page: webview_map.html 23 10. Android – UI – The WebKit Browser WebKit Browser 23 Part2. WebView3: Porting to Android the Google Map V3 App. Putting the pieces together: Place a WebView in the main.xml file Place html page in the assets folder Add permission requests to manifest Connect to Java code Warning: tested on Android 2.2 24 10. Android – UI – The WebKit Browser WebKit Browser 24 Part2. WebView3: Porting to Android the Google Map V3 App. Add the following permission requests to the AndroidManifest.xml file Map image shown on an Android device 25 10. Android – UI – The WebKit Browser WebKit Browser 25 Part2. WebView3: Porting to Android the Google Map V3 App. public class Main extends Activity { WebView browser; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // connect browser to local html file showing map browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.loadUrl("file:///android_asset/webview_map.html"); } } 26 10. Android – UI – The WebKit Browser WebKit Browser 26 Part3. WebView4: Android & Google Map V3 App (real locations) Ví dụ này kết hợp hai ví dụ trước: Mục tiêu là dùng một đối tượng Android để truyền dữ liệu ‘vị trí thực’ cho một trang html. Trang html chứa một đoạn mã JavaScript vẽ bản đồ có tâm là tọa độ đã cho. Warning: Make sure your target is: Google APIs (API Level 8) or higher. Vĩ độ (Latitude) và kinh độ (longitude) do thiết bị xác định. Ảnh chụp từ điện thoại Android. 27 10. Android – UI – The WebKit Browser WebKit Browser 27 Part2. WebView3: Porting to Android the Google Map V3 App. Putting the pieces together: Place a WebView in the main.xml file Place html page in the assets folder Add permission requests to manifest Connect to Java code Warning: tested on Android 2.2 28 10. Android – UI – The WebKit Browser WebKit Browser 28 Part3. WebView4: Android & Google Map V3 App (real locations) Google Maps JavaScript API v3 Example: Marker Simple html { height: 100% } body { height: 100%; margin: 0px; padding: 0px } #map_canvas { height: 100% } function initialize() { //var myLatlng = new google.maps.LatLng(41.5020952, -81.6789717); var myLatlng = new google.maps.LatLng(locater.getLatitude(), locater.getLongitude()); var myOptions = { zoom: 17, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP } var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions); var marker = new google.maps.Marker({ position: myLatlng, map: map }); } Html page creates a map using ‘real’ coordinates passed in the ‘locater’ object 29 10. Android – UI – The WebKit Browser WebKit Browser 29 Part3. WebView4: Android & Google Map V3 App (real locations) public class Main extends Activity implements LocationListener { private static final String MAP_URL = ""; private WebView browser; //Location mostRecentLocation; LocationManager locationManager; MyLocater locater = new MyLocater(); @Override protected void onDestroy() { super.onDestroy(); // cut location service requests locationManager.removeUpdates(this); } private void getLocation() { locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); // use GPS (you must be outside) //criteria.setAccuracy(Criteria.ACCURACY_COARSE); // towers, wifi String provider = locationManager.getBestProvider(criteria, true); // In order to make sure the device is getting the location, request // updates [wakeup after changes of: 1 sec. or 0 meter] locationManager.requestLocationUpdates(provider, 1, 0, this); locater.setNewLocation(locationManager.getLastKnownLocation(provider)); } 30 10. Android – UI – The WebKit Browser WebKit Browser 30 Part3. WebView4: Android & Google Map V3 App (real locations) @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); getLocation(); setupbrowser(); this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } /** Sets up the browser object and loads the URL of the page **/ private void setupbrowser() { final String centerURL = "javascript:centerAt(" + locater.getLatitude() + "," + locater.getLongitude() + ")"; // set up the browser to show location results browser = (WebView) findViewById(R.id.webview); browser.getSettings().setJavaScriptEnabled(true); browser.addJavascriptInterface(locater, "locater"); browser.loadUrl("file:///android_asset/webview_map.html"); 31 10. Android – UI – The WebKit Browser WebKit Browser 31 Part3. WebView4: Android & Google Map V3 App (real locations) // Wait for the page to load then send the location information browser.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { browser.loadUrl(centerURL); } }); } @Override public void onLocationChanged(Location location) { String lat = String.valueOf(location.getLatitude()); String lon = String.valueOf(location.getLongitude()); Toast.makeText(getApplicationContext(), lat + "\n" + lon, 1).show(); locater.setNewLocation(location); } @Override public void onProviderDisabled(String provider) { // needed by Interface. Not used } @Override public void onProviderEnabled(String provider) { // needed by Interface. Not used } @Override public void onStatusChanged(String provider, int status, Bundle extras) { // needed by Interface. Not used } 32 10. Android – UI – The WebKit Browser WebKit Browser 32 Part3. WebView4: Android & Google Map V3 App (real locations) // /////////////////////////////////////////////////////////////////// // An object of type "MyLocater" will be used to pass data back and // forth between the Android app and the JS code behind the html page. // /////////////////////////////////////////////////////////////////// public class MyLocater { private Location mostRecentLocation; public void setNewLocation(Location newCoordinates){ mostRecentLocation = newCoordinates; } public double getLatitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLatitude(); } public double getLongitude() { if (mostRecentLocation == null) return (0); else return mostRecentLocation.getLongitude(); } }// MyLocater }//class 33 33 10. Android – UI – The WebKit Browser WebKit Browser 33 Questions ?
File đính kèm:
- Lập trình Android tiếng Việt - Chapter 10 Android The WebKit Browser.pptx