html与js与mysql_WebView加载html与JS交互
一、加載Html的幾種方法
直接在Activity中實例化WebView
WebView webview =new WebView(this);
webview.loadUrl(......);
在XML中生命webview
WebView webView = (WebView) findViewById(R.id.webview);
載入工程內部頁面 page.html存儲在工程文件的assets根目錄下
webView = (WebView) findViewById(R.id.webview);
webView.loadUrl("file:///file:///android_asset/page.html");
二、加載頁面時幾種簡單API使用
設置縮放
mWebView.getSettings().setBuiltInZoomControls(true);
在webview添加對js的支持
setting.setJavaScriptEnabled(true);//支持js
添加對中文支持
setting.setDefaultTextEncodingName("GBK");//設置字符編碼
設置頁面滾動條風格
webView.setScrollBarStyle(0);//滾動條風格,為0指滾動條不占用空間,直接覆蓋在網頁上
取消滾動條
this.setScrollBarStyle(SCROLLBARS_OUTSIDE_OVERLAY);
listview,webview中滾動拖動到頂部或者底部時的陰影(滑動到項部或底部不固定)
WebView.setOverScrollMode(View.OVER_SCROLL_NEVER);
三、瀏覽器優化操作處理:
WebView默認用系統自帶瀏覽器處理頁面跳轉。為了讓頁面跳轉在當前WebView中進行,
重寫WebViewClient
mWebView.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);//使用當前WebView處理跳轉
return true;//true表示此事件在此處被處理,不需要再廣播
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
//有頁面跳轉時被回調
}
@Override
public void onPageFinished(WebView view, String url) {
//頁面跳轉結束后被回調
}
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Toast.makeText(WebViewDemo.this, "Oh no! " + description, Toast.LENGTH_SHORT).show();
}
});
當WebView內容影響UI時調用WebChromeClient的方法
mWebView.setWebChromeClient(new WebChromeClient() {
/**
* 處理JavaScript Alert事件
*/
@Override
public boolean onJsAlert(WebView view, String url,
String message, final JsResult result) {
//用Android組件替換
new AlertDialog.Builder(WebViewDemo.this)
.setTitle("JS提示")
.setMessage(message)
.setPositiveButton(android.R.string.ok, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
})
.setCancelable(false)
.create().show();
return true;
}
});
按BACK鍵時,不會返回跳轉前的頁面,而是退出本Activity,重寫onKeyDown()方法來解決此問題
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//處理WebView跳轉返回
if ((keyCode == KeyEvent.KEYCODE_BACK) && mWebView.canGoBack()) {
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
private class JsToJava {
public void jsMethod(String paramFromJS) {
Log.i("CDH", paramFromJS);
}
}
四、WebView與JS交互
總綱
/*
綁定Java對象到WebView,這樣可以讓JS與Java通信(JS訪問Java方法)
第一個參數是自定義類對象,映射成JS對象
第二個參數是第一個參數的JS別名
調用示例:
mWebView.loadUrl("javascript:window.stub.jsMethod('param')");
*/
mWebView.addJavascriptInterface(new JsToJava(), "stub");
final EditText mEditText = (EditText)findViewById(R.id.web_view_text);
findViewById(R.id.web_view_search).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
String url = mEditText.getText().toString();
if (url == null || "".equals(url)) {
Toast.makeText(WebViewDemo.this, "請輸入URL", Toast.LENGTH_SHORT).show();
} else {
if (!url.startsWith("http:") && !url.startsWith("file:")) {
url = "http://" + url;
}
mWebView.loadUrl(url);
}
}
});
//默認頁面
mWebView.loadUrl("file:///android_asset/js_interact_demo.html");
}
撲捉加載頁面JS的過程
注意到webview提供的兩個方法:
setWebChromeClient方法正是可以處理progress的加載,此外,還可以處理js對話框,在webview中顯示icon圖標等。
對于setWebViewClient方法,一般用來處理html的加載(需要重載onPageStarted(WebView view, String url, Bitmap favicon))、關閉(需要重載onPageFinished(WebViewview, String url)方法)。
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {// 載入進度改變而觸發
if (progress == 100) {
handler.sendEmptyMessage(1);// 如果全部載入,隱藏進度對話框
}
super.onProgressChanged(view, progress);
}
});
獲取java中的數據:單獨構建一個接口,作為處理js與java的數據交互的橋梁
封裝的代碼AndroidToastForJs.java
public class AndroidToastForJs {
private Context mContext;
public AndroidToastForJs(Context context){
this.mContext = context;
}
//webview中調用toast原生組件
public void showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
//webview中求和
public int sum(int a,int b){
return a+b;
}
//以json實現webview與js之間的數據交互
public String jsontohtml(){
JSONObject map;
JSONArray array = new JSONArray();
try {
map = new JSONObject();
map.put("name","aaron");
map.put("age", 25);
map.put("address", "中國上海");
array.put(map);
map = new JSONObject();
map.put("name","jacky");
map.put("age", 22);
map.put("address", "中國北京");
array.put(map);
map = new JSONObject();
map.put("name","vans");
map.put("age", 26);
map.put("address", "中國深圳");
map.put("phone","13888888888");
array.put(map);
} catch (JSONException e) {
e.printStackTrace();
}
return array.toString();
}
}
Webview提供的傳入js的方法:
webView.addJavascriptInterface(new AndroidToastForJs(mContext), "JavaScriptInterface");
Html頁面jsonData.html設計的部分代碼如下
var result = JavaScriptInterface.jsontohtml();
var obj = eval("("+result+")");//解析json字符串
function showAndroidToast(toast)
{
JavaScriptInterface.showToast(toast);
}
function getjsonData(){
var result = JavaScriptInterface.jsontohtml();
var obj = eval("("+result+")");//解析json字符串
for(i=0;i
var user=obj[i];
document.write("
姓名:"+user.name+"
");document.write("
年齡:"+user.age+"
");document.write("
地址:"+user.address+"
");if(user.phone!=null){
document.write("
手機號碼:"+user.address+"
");}
}
}
function list(){
document.write("
another
");}
Android via Interface
I'm ,click to see my info
");");");Page Footer
問題解決:
多圖片網頁手機加載數度慢
1. 建議先用 webView.getSettings().setBlockNetworkImage(true); 將圖片下載阻塞
2. 在瀏覽器的OnPageFinished事件中設置 webView.getSettings().setBlockNetworkImage(false);
通過圖片的延遲載入,讓網頁能更快地顯示
HTML5交互:
HTML5本地存儲在Android中的應用
HTML5提供了2種客戶端存儲數據新方法:
localStorage 沒有時間限制
sessionStorage 針對一個Session的數據存儲
localStorage.lastname="Smith";
document.write(localStorage.lastname);
sessionStorage.lastname="Smith";
document.write(sessionStorage.lastname);
WebStorage的API:
//清空storage
localStorage.clear();
//設置一個鍵值
localStorage.setItem(“yarin”,“yangfegnsheng”);
//獲取一個鍵值
localStorage.getItem(“yarin”);
//獲取指定下標的鍵的名稱(如同Array)
localStorage.key(0);
//return “fresh” //刪除一個鍵值
localStorage.removeItem(“yarin”);
注意一定要在設置中開啟哦
setDomStorageEnabled(true)
在Android中進行操作:
//啟用數據庫
webSettings.setDatabaseEnabled(true);
String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
//設置數據庫路徑
webSettings.setDatabasePath(dir);
//使用localStorage則必須打開
webSettings.setDomStorageEnabled(true);
//擴充數據庫的容量(在WebChromeClinet中實現)
public void onExceededDatabaseQuota(String url, String databaseIdentifier, long currentQuota,
long estimatedSize, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(estimatedSize * 2);
}
在JS中按常規進行數據庫操作:
tHandler, errorHandler);
}
);
}
function dataSelectHandler(transaction, results){
// Handle the results
for (var i=0; i
var row = results.rows.item(i);
var newFeature = new Object();
newFeature.name = row['name'];
newFeature.decs = row['desc'];
document.getElementById("name").innerHTML="name:"+newFeature.name;
document.getElementById("desc").innerHTML="desc:"+newFeature.decs;
}
}
function updateData(){
YARINDB.transaction(
function (transaction) {
var data = ['fengsheng yang','I am fengsheng'];
transaction.executeSql("UPDATE yarin SET name=?, desc=? WHERE id = 1", [data[0], data[1]]);
}
);
selectAll();
}
function ddeleteTables(){
YARINDB.transaction(
function (transaction) {
transaction.executeSql("DROP TABLE yarin;", [], nullDataHandler, errorHandler);
}
);
console.log("Table 'page_settings' has been dropped.");
}
注意onLoad中的初始化工作
function initLocalStorage(){
if (window.localStorage) {
textarea.addEventListener("keyup", function() {
window.localStorage["value"] = this.value;
window.localStorage["time"] = new Date().getTime();
}, false);
} else {
alert("LocalStorage are not supported in this browser.");
}
}
window.onload = function() {
initDatabase();
initLocalStorage();
}
HTML5地理位置服務在Android中的應用:
Android中:
//啟用地理定位
webSettings.setGeolocationEnabled(true);
//設置定位的數據庫路徑
webSettings.setGeolocationDatabasePath(dir);
//配置權限(同樣在WebChromeClient中實現)
public void onGeolocationPermissionsShowPrompt(String origin,
GeolocationPermissions.Callback callback) {
callback.invoke(origin, true, false);
super.onGeolocationPermissionsShowPrompt(origin, callback);
}
在Manifest中添加權限
HTML5中 通過navigator.geolocation對象獲取地理位置信息:
常用的navigator.geolocation對象有以下三種方法:
//獲取當前地理位置
navigator.geolocation.getCurrentPosition(success_callback_function, error_callback_function, position_options)
//持續獲取地理位置
navigator.geolocation.watchPosition(success_callback_function, error_callback_function, position_options)
清除持續獲取地理位置事件
navigator.geolocation.clearWatch(watch_position_id)
----其中success_callback_function為成功之后處理的函數,error_callback_function為失敗之后返回的處理函數,參數position_options是配置項
在JS中的代碼:
//定位
function get_location() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy:false,maximumAge:1000,timeout:15000});
} else {
alert("Your browser does not support HTML5 geoLocation");
}
}
function show_map(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var city = position.coords.city;
//telnet localhost 5554
//geo fix -82.411629 28.054553
//geo fix -121.45356 46.51119 4392
//geo nmea $GPGGA,001431.092,0118.2653,N,10351.1359,E,0,00,,-19.6,M,4.1,M,,0000*5B
document.getElementById("Latitude").innerHTML="latitude:"+latitude;
document.getElementById("Longitude").innerHTML="longitude:"+longitude;
document.getElementById("City").innerHTML="city:"+city;
}
function handle_error(err) {
switch (err.code) {
case 1:
alert("permission denied");
break;
case 2:
alert("the network is down or the position satellites can't be contacted");
break;
case 3:
alert("time out");
break;
default:
alert("unknown error");
break;
}
}
----其中position對象包含很多數據 error代碼及選項 可以查看文檔
構建HTML5離線應用:
需要提供一個cache manifest文件,理出所有需要在離線狀態下使用的資源
例如:
CACHE MANIFEST
#這是注釋
images/sound-icon.png
images/background.png
clock.html
clock.css
clock.js
NETWORK:
test.cgi
CACHE:
style/default.css
FALLBACK:
/files/projects /projects
在html標簽中聲明 ?
HTML5離線應用更新緩存機制
分為手動更新和自動更新2種
自動更新:
在cache manifest文件本身發生變化時更新緩存 資源文件發生變化不會觸發更新
手動更新:
使用window.applicationCache
if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.update();
}
在線狀態檢測
HTML5 提供了兩種檢測是否在線的方式:navigator.online(true/false) 和 online/offline事件。
在Android中構建離線應用:
//開啟應用程序緩存
webSettingssetAppCacheEnabled(true);
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//設置應用緩存的路徑
webSettings.setAppCachePath(dir);
//設置緩存的模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//設置應用緩存的最大尺寸
webSettings.setAppCacheMaxSize(1024*1024*8);
//擴充緩存的容量
public void onReachedMaxAppCacheSize(long spaceNeeded,
long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) {
quotaUpdater.updateQuota(spaceNeeded * 2);
}
Android與JS之間的互相調用
在JS中調用Android的函數方法
final class InJavaScript {
public void runOnAndroidJavaScript(final String str) {
handler.post(new Runnable() {
public void run() {
TextView show = (TextView) findViewById(R.id.textview);
show.setText(str);
}
});
}
}
//把本類的一個實例添加到js的全局對象window中,
//這樣就可以使用window.injs來調用它的方法
webView.addJavascriptInterface(new InJavaScript(), "injs");
在JavaScript中調用:
function sendToAndroid(){
var str = "Cookie call the Android method from js";
window.injs.runOnAndroidJavaScript(str);//調用android的函數
}
在Android中調用JS的方法:
在JS中的方法:
function getFromAndroid(str){
document.getElementById("android").innerHTML=str;
}
在Android調用該方法:
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//調用javascript中的方法
webView.loadUrl("javascript:getFromAndroid('Cookie call the js function from Android')");
}
});
Android中處理JS的警告,對話框等
在Android中處理JS的警告,對話框等需要對WebView設置WebChromeClient對象:
//設置WebChromeClient
webView.setWebChromeClient(new WebChromeClient(){
//處理javascript中的alert
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
//構建一個Builder來顯示網頁中的對話框
Builder builder = new Builder(MainActivity.this);
builder.setTitle("Alert");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
//處理javascript中的confirm
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
Builder builder = new Builder(MainActivity.this);
builder.setTitle("confirm");
builder.setMessage(message);
builder.setPositiveButton(android.R.string.ok,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
});
builder.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
});
builder.setCancelable(false);
builder.create();
builder.show();
return true;
};
@Override
//設置網頁加載的進度條
public void onProgressChanged(WebView view, int newProgress) {
MainActivity.this.getWindow().setFeatureInt(Window.FEATURE_PROGRESS, newProgress * 100);
super.onProgressChanged(view, newProgress);
}
//設置應用程序的標題title
public void onReceivedTitle(WebView view, String title) {
MainActivity.this.setTitle(title);
super.onReceivedTitle(view, title);
}
});
Android中的調試:
通過JS代碼輸出log信息:
Js代碼: console.log("Hello World");
Log信息: Console: Hello World http://www.example.com/hello.html :82
在WebChromeClient中實現onConsoleMesaage()回調方法,讓其在LogCat中打印信息:
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
public void onConsoleMessage(String message, int lineNumber, String sourceID) {
Log.d("MyApplication", message + " -- From line "
+ lineNumber + " of "
+ sourceID);
}
});
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cm) {
Log.d("MyApplication", cm.message() + " -- From line "
+ cm.lineNumber() + " of "
+ cm.sourceId() );
return true;
}
});
---ConsoleMessage 還包括一個 MessageLevel 表示控制臺傳遞信息類型。
您可以用messageLevel()查詢信息級別,以確定信息的嚴重程度,然后使用適當的Log方法或采取其他適當的措施。
后面的內容在下篇中繼續
總結
以上是生活随笔為你收集整理的html与js与mysql_WebView加载html与JS交互的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 联想高性能服务器,Lenovo|EMC推
- 下一篇: mysql主从配置访问_Mysql主从配