● Android设备多分辨率的问题javascript
Android浏览器默认预览模式浏览 会缩小页面 WebView中则会以原始大小显示css
Android浏览器和WebView默认为mdpi。hdpi至关于mdpi的1.5倍 ldpi至关于0.75倍html
三种解决方式:1 viewport属性 2 CSS控制 3 JS控制java
1 viewport属性放在HTML的<meta>中android
Html代码
<SPAN style="FONT-SIZE: x-small"> <head>
<title>Exmaple</title>
<meta name=”viewport” content=”width=device-width,user-scalable=no”/>
</head></SPAN>git
meta中viewport的属性以下web
Html代码
<SPAN style="FONT-SIZE: x-small"> <meta name="viewport" content=" height = [pixel_value | device-height] , width = [pixel_value | device-width ] , initial-scale = float_value , minimum-scale = float_value , maximum-scale = float_value , user-scalable = [yes | no] , target-densitydpi = [dpi_value | device-dpi | high-dpi | medium-dpi | low-dpi] " /></SPAN>数据库
2 CSS控制设备密度windows
为每种密度建立独立的样式表(注意其中的webkit-device-pixel-ratio 3个数值对应3种分辨率)浏览器
Html代码
<link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.5)" href="hdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 1.0)" href="mdpi.css" /> <link rel="stylesheet" media="screen and (-webkit-device-pixel-ratio: 0.75)" href="ldpi.css" />
在一个样式表中,指定不一样的样式
Html代码
#header {
<SPAN style="WHITE-SPACE: pre"> </SPAN> background:url(medium-density-image.png);
}
@media screen and (-webkit-device-pixel-ratio: 1.5) {
// CSS for high-density screens
#header {
background:url(high-density-image.png);
}
}
@media screen and (-webkit-device-pixel-ratio: 0.75) {
// CSS for low-density screens
#header {
background:url(low-density-image.png);
}
}
Html代码
<meta name="viewport" content="target-densitydpi=device-dpi, width=device-width" />
3 JS控制
Android浏览器和WebView支持查询当前设别密度的DOM特性
window.devicePixelRatio 一样值有3个(0.75,1,1.5对应3种分辨率)
JS中查询设备密度的方法
Js代码 if (window.devicePixelRatio == 1.5) {
alert("This is a high-density screen");
} else if (window.devicePixelRation == 0.75) {
alert("This is a low-density screen");
}
● Android中构建HTML5应用
使用WebView控件 与其余控件的使用方法相同 在layout中使用一个<WebView>标签
WebView不包括导航栏,地址栏等完整浏览器功能,只用于显示一个网页
在WebView中加载Web页面,使用loadUrl()
Java代码 WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.loadUrl("http://www.example.com");
注意在manifest文件中加入访问互联网的权限:
Xml代码
<uses-permission android:name="android.permission.INTERNET" />
在Android中点击一个连接,默认是调用应用程序来启动,所以WebView须要代为处理这个动做 经过WebViewClient
Java代码
//设置WebViewClient
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
});
这个WebViewClient对象是能够本身扩展的,例如
Java代码
private class MyWebViewClient extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (Uri.parse(url).getHost().equals("www.example.com")) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
以后:
Java代码
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new MyWebViewClient());
另外出于用户习惯上的考虑 须要将WebView表现得更像一个浏览器,也就是须要能够回退历史记录
所以须要覆盖系统的回退键 goBack,goForward可向前向后浏览历史页面
Java代码
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
myWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
Java代码 WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
(这里的webSetting用处很是大 能够开启不少设置 在以后的本地存储,地理位置等之中都会使用到)
1 在JS中调用Android的函数方法
首先 须要在Android程序中创建接口
Java代码 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);
}
});
}
}
Java代码 //把本类的一个实例添加到js的全局对象window中,
//这样就可使用windows.injs来调用它的方法
webView.addJavascriptInterface(new InJavaScript(), "injs");
在JavaScript中调用 Js代码 function sendToAndroid(){
var str = "Cookie call the Android method from js";
windows.injs.runOnAndroidJavaScript(str);//调用android的函数
}
2 在Android中调用JS的方法
在JS中的方法: Js代码 function getFromAndroid(str){
document.getElementByIdx_x_x_x("android").innerHTML=str;
}
在Android调用该方法 Java代码 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')");
}
});
3 Android中处理JS的警告,对话框等 在Android中处理JS的警告,对话框等须要对WebView设置WebChromeClient对象 Java代码
//设置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代码
Js代码: console.log("Hello World");
Log信息: Console: Hello World http://www.example.com/hello.html :82
在WebChromeClient中实现onConsoleMesaage()回调方法,让其在LogCat中打印信息 Java代码
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);
}
});
以及 Java代码
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方法或采起其余适当的措施。
● HTML5本地存储在Android中的应用 HTML5提供了2种客户端存储数据新方法: localStorage 没有时间限制 sessionStorage 针对一个Session的数据存储
Js代码
<script type="text/javascript"> localStorage.lastname="Smith"; document.write(localStorage.lastname); </script>
<script type="text/javascript"> sessionStorage.lastname="Smith"; document.write(sessionStorage.lastname); </script>
WebStorage的API:
Js代码 //清空storage
localStorage.clear();
//设置一个键值
localStorage.setItem(“yarin”,“yangfegnsheng”);
//获取一个键值
localStorage.getItem(“yarin”);
//获取指定下标的键的名称(如同Array)
localStorage.key(0);
//return “fresh” //删除一个键值
localStorage.removeItem(“yarin”);
注意必定要在设置中开启哦
setDomStorageEnabled(true)
在Android中进行操做
Java代码 //启用数据库
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中按常规进行数据库操做
Js代码 function initDatabase() {
try {
if (!window.openDatabase) {
alert('Databases are not supported by your browser');
} else {
var shortName = 'YARINDB';
var version = '1.0';
var displayName = 'yarin db';
var maxSize = 100000; // in bytes
YARINDB = openDatabase(shortName, version, displayName, maxSize);
createTables();
selectAll();
}
} catch(e) {
if (e == 2) {
// Version mismatch.
console.log("Invalid database version.");
} else {
console.log("Unknown error "+ e +".");
}
return;
}
}
function createTables(){
YARINDB.transaction(
function (transaction) {
transaction.executeSql('CREATE TABLE IF NOT EXISTS yarin(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL,desc TEXT NOT NULL);', [], nullDataHandler, errorHandler);
}
);
insertData();
}
function insertData(){
YARINDB.transaction(
function (transaction) {
//Starter data when page is initialized
var data = ['1','yarin yang','I am yarin'];
transaction.executeSql("INSERT INTO yarin(id, name, desc) VALUES (?, ?, ?)", [data[0], data[1], data[2]]); } );
}
function errorHandler(transaction, error){
if (error.code==1){
// DB Table already exists
} else {
// Error is a human-readable string.
console.log('Oops. Error was '+error.message+' (Code '+error.code+')');
}
return false;
}
function nullDataHandler(){
console.log("SQL Query Succeeded");
}
function selectAll(){
YARINDB.transaction(
function (transaction) {
transaction.executeSql("SELECT * FROM yarin;", [], dataSelectHandler, errorHandler);
}
);
}
function dataSelectHandler(transaction, results){
// Handle the results
for (var i=0; i<results.rows.length; i++) {
var row = results.rows.item(i);
var newFeature = new Object();
newFeature.name = row['name'];
newFeature.decs = row['desc'];
document.getElementByIdx_x_x_x("name").innerHTML="name:"+newFeature.name; document.getElementByIdx_x_x_x("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中
Java代码 //启用地理定位
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中添加权限
Xml代码 <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
HTML5中 经过navigator.geolocation对象获取地理位置信息 经常使用的navigator.geolocation对象有如下三种方法:
Js代码 //获取当前地理位置
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中的代码 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.getElementByIdx_x_x_x("Latitude").innerHTML="latitude:"+latitude;
document.getElementByIdx_x_x_x("Longitude").innerHTML="longitude:"+longitude;
document.getElementByIdx_x_x_x("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文件,理出全部须要在离线状态下使用的资源 例如 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标签中声明 <html manifest="clock.manifest">
HTML5离线应用更新缓存机制 分为手动更新和自动更新2种 自动更新: 在cache manifest文件自己发生变化时更新缓存 资源文件发生变化不会触发更新 手动更新: 使用window.applicationCache Js代码 if (window.applicationCache.status == window.applicationCache.UPDATEREADY) {
window.applicationCache.update();
}
在线状态检测 HTML5 提供了两种检测是否在线的方式:navigator.online(true/false) 和 online/offline事件。
在Android中构建离线应用 Java代码 //开启应用程序缓存
webSettingssetAppCacheEnabled(true);
String dir = this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath();
//设置应用缓存的路径
webSettings.setAppCachePath(dir);
//设置缓存的模式
webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
//设置应用缓存的最大尺寸
webSettings.setAppCacheMaxSize(102410248);
//扩充缓存的容量 public void onReachedMaxAppCacheSize(long spaceNeeded, long totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { quotaUpdater.updateQuota(spaceNeeded * 2); }