Android HTML5 开发
来源:互联网 发布:java的https通信 编辑:程序博客网 时间:2024/06/03 19:56
转自:http://blog.sina.com.cn/s/blog_83940dfb0100yrfm.html
● Android设备多分辨率的问题
Android浏览器默认预览模式浏览 会缩小页面 WebView中则会以原始大小显示
Android浏览器和WebView默认为mdpi。hdpi相当于mdpi的1.5倍 ldpi相当于0.75倍
三种解决方式:1 viewport属性 2 CSS控制 3 JS控制
1 viewport属性放在HTML的<meta>中
- <SPAN
style="FONT-SIZE: x-small" > -
-
name=”viewport” content=”width=device-width,user-scalable=no”/> -
meta中viewport的属性如下
- <SPAN
style="FONT-SIZE: x-small" >name="viewport" -
-
= [pixel_value | device-height] , -
= [pixel_value | device-width ] , -
= float_value, -
= float_value, -
= float_value, -
= [yes | no] , -
= [dpi_value | device-dpi | -
high-dpi | medium-dpi | low-dpi] -
" -
2 CSS控制设备密度
为每种密度创建独立的样式表(注意其中的webkit-device-pixel-ratio 3个数值对应3种分辨率)
- <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" />
在一个样式表中,指定不同的样式
- #header
{ -
<SPAN style="WHITE-SPACE: pre" >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); -
} - }
- <meta
name="viewport" content="target-densitydpi=device-dpi, width=device-width" />
Android浏览器和WebView支持查询当前设别密度的DOM特性
window.devicePixelRatio 同样值有3个(0.75,1,1.5对应3种分辨率)
JS中查询设备密度的方法
- if
(window.devicePixelRatio == 1.5) { -
alert( is );a high-density screen" - }
else if (window.devicePixelRation == 0.75) { -
alert( is );a low-density screen" - }
● Android中构建HTML5应用
使用WebView控件 与其他控件的使用方法相同 在layout中使用一个<WebView>标签
WebView不包括导航栏,地址栏等完整浏览器功能,只用于显示一个网页
在WebView中加载Web页面,使用loadUrl()
- WebView
myWebView = (WebView) findViewById(R.id.webview); - myWebView.loadUrl("http://www.example.com");
注意在manifest文件中加入访问互联网的权限:
- <uses-permission
android:name="android.permission.INTERNET" />
在Android中点击一个链接,默认是调用应用程序来启动,因此WebView需要代为处理这个动作 通过WebViewClient
- //设置WebViewClient
- webView.setWebViewClient(new
WebViewClient(){ -
boolean shouldOverrideUrlLoading (WebView view, String url) { -
view.loadUrl(url); -
true; -
} -
void onPageFinished(WebView view, String url) { -
url); -
} -
void onPageStarted(WebView view, String url, Bitmap favicon) { -
url, favicon); -
} - });
这个WebViewClient对象是可以自己扩展的,例如
- private
class MyWebViewClient extendsWebViewClient { -
boolean shouldOverrideUrlLoading (WebView view, String url) { -
(Uri.parse(url).getHost().equals( "www.example.com")){ -
false; -
} -
Intent intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)); -
startActivity(intent); -
true; -
} - }
之后:
- WebView
myWebView = (WebView) findViewById(R.id.webview); - myWebView.setWebViewClient(new
MyWebViewClient());
另外出于用户习惯上的考虑 需要将WebView表现得更像一个浏览器,也就是需要可以回退历史记录
因此需要覆盖系统的回退键 goBack,goForward可向前向后浏览历史页面
- public
boolean onKeyDown( intkeyCode, KeyEvent event) { -
((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() { -
myWebView.goBack(); -
true; -
} -
super.onKeyDown(keyCode, event); - }
- WebView
myWebView = (WebView) findViewById(R.id.webview); - WebSettings
webSettings = myWebView.getSettings(); - webSettings.setJavaScriptEnabled(true);
(这里的webSetting用处非常大 可以开启很多设置 在之后的本地存储,地理位置等之中都会使用到)1 在JS中调用Android的函数方法 首先 需要在Android程序中建立接口
- final
class InJavaScript { -
void runOnAndroidJavaScript( finalString str) { -
handler.post( Runnable() { -
void run() { -
TextView show = (TextView) findViewById(R.id.textview); -
show.setText(str); -
} -
}); -
} -
}
- //把本类的一个实例添加到js的全局对象window中,
- //这样就可以使用windows.injs来调用它的方法
- webView.addJavascriptInterface(new
InJavaScript(), "injs");
在JavaScript中调用
- function
sendToAndroid(){ -
str "Cookie= call ;the Android method from js" -
windows.injs.runOnAndroidJavaScript(str); - }
2 在Android中调用JS的方法 在JS中的方法:
- function
getFromAndroid(str){ -
document.getElementByIdx_x_x_x( - }
在Android调用该方法
- Button
button = (Button) findViewById(R.id.button); -
button.setOnClickListener( OnClickListener() { -
void onClick(View arg0) { -
-
webView.loadUrl( call );the js function from Android')" -
} -
});
3 Android中处理JS的警告,对话框等在Android中处理JS的警告,对话框等需要对WebView设置WebChromeClient对象
- //设置WebChromeClient
- webView.setWebChromeClient(new
WebChromeClient(){ -
-
boolean onJsAlert(WebView finalview, String url, String message, JsResult result) { -
-
Builder builder = Builder(MainActivity. this); -
builder.setTitle( -
builder.setMessage(message); -
builder.setPositiveButton(android.R.string.ok, -
AlertDialog.OnClickListener() { -
void onClick(DialogInterface intdialog, which) { -
result.confirm(); -
} -
}); -
builder.setCancelable( -
builder.create(); -
builder.show(); -
true; -
}; -
-
boolean onJsConfirm(WebView finalview, String url, String message, JsResult result) { -
Builder builder = Builder(MainActivity. this); -
builder.setTitle( -
builder.setMessage(message); -
builder.setPositiveButton(android.R.string.ok, -
AlertDialog.OnClickListener() { -
void onClick(DialogInterface intdialog, which) { -
result.confirm(); -
} -
}); -
builder.setNegativeButton(android.R.string.cancel, -
DialogInterface.OnClickListener() { -
void onClick(DialogInterface intdialog, which) { -
result.cancel(); -
} -
}); -
builder.setCancelable( -
builder.create(); -
builder.show(); -
true; -
}; -
-
-
-
void onProgressChanged(WebView intview, newProgress) { -
MainActivity. newProgress 100);* -
newProgress); -
} -
-
-
void onReceivedTitle(WebView view, String title) { -
MainActivity. -
title); -
} - });
● Android中的调试通过JS代码输出log信息
- Js代码:
console.log( "HelloWorld" ); - Log信息:
Console: //www.example.com/hello.htmlHello World http: :82
在WebChromeClient中实现onConsoleMesaage()回调方法,让其在LogCat中打印信息
- WebView
myWebView = (WebView) findViewById(R.id.webview); - myWebView.setWebChromeClient(new
WebChromeClient() { -
void onConsoleMessage(String intmessage, lineNumber, String sourceID) { -
Log.d( message "+ -- From line " -
+ lineNumber + of " -
+ sourceID); -
} - });
以及
- WebView
myWebView = (WebView) findViewById(R.id.webview); - myWebView.setWebChromeClient(new
WebChromeClient() { -
boolean onConsoleMessage(ConsoleMessage cm) { -
Log.d( cm.message() "+ -- From line " -
+ cm.lineNumber() + of " -
+ cm.sourceId() ); -
true; -
} - });
*ConsoleMessage 还包括一个 MessageLevel 表示控制台传递信息类型。 您可以用messageLevel()查询信息级别,以确定信息的严重程度,然后使用适当的Log方法或采取其他适当的措施。 ● HTML5本地存储在Android中的应用HTML5提供了2种客户端存储数据新方法:localStorage 没有时间限制sessionStorage 针对一个Session的数据存储
- <script
type= "text/javascript"> -
localStorage.lastname= -
document.write(localStorage.lastname); - </script>
- <script
type= "text/javascript"> -
sessionStorage.lastname= -
document.write(sessionStorage.lastname); - </script>
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 longurl, String databaseIdentifier, currentQuota, -
estimatedSize, longtotalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { -
quotaUpdater.updateQuota(estimatedSize * - }
在JS中按常规进行数据库操作
- function
initDatabase() { - try
{ -
(!window.openDatabase) { -
alert( are );not supported by your browser' -
} { -
shortName 'YARINDB';= -
version '1.0';= -
displayName 'yarin= db' ; -
maxSize //= 100000; in bytes -
YARINDB = openDatabase(shortName, version, displayName, maxSize); -
createTables(); -
selectAll(); -
} - }
catch(e) { -
(e == 2) { -
Version mismatch. -
console.log( database );version." -
} { -
console.log( error +" e ".");+ -
} -
- }
- }
-
- function
createTables(){ -
YARINDB.transaction( -
(transaction) { -
transaction.executeSql( 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( -
(transaction) { -
data when page is initialized -
data '1','yarin= [ yang' ,'Iam ];yarin' -
-
transaction.executeSql( INTO ,yarin(id, name, desc) VALUES (?, ?, ?)" [data[0], data[1], data[2]]); -
} -
); - }
-
- function
errorHandler(transaction, error){ -
(error.code==1){ -
DB Table already exists -
} { -
Error is a human-readable string. -
console.log( Error was ' (Code +error.code+')');' -
} -
false; - }
-
-
- function
nullDataHandler(){ -
console.log( Query );Succeeded" - }
-
- function
selectAll(){ -
YARINDB.transaction( -
(transaction) { -
transaction.executeSql( * ,FROM yarin;" [], dataSelectHandler, errorHandler); -
} -
); - }
-
- function
dataSelectHandler(transaction, results){ -
Handle the results -
( vari=0; i<results.rows.length; i++) { -
row = results.rows.item(i); -
newFeature new= Object(); -
newFeature.name = row[ -
newFeature.decs = row[ -
-
document.getElementByIdx_x_x_x( -
document.getElementByIdx_x_x_x( -
} - }
-
- function
updateData(){ -
YARINDB.transaction( -
(transaction) { -
data 'fengsheng= [ yang' ,'Iam ];fengsheng' -
transaction.executeSql( yarin ,SET name=?, desc=? WHERE id = 1" [data[0], data[1]]); -
} -
); -
selectAll(); - }
-
- function
ddeleteTables(){ -
YARINDB.transaction( -
(transaction) { -
transaction.executeSql( TABLE ,yarin;" [], nullDataHandler, errorHandler); -
} -
); -
console.log( 'page_settings' );has been dropped." - }
- 注意onLoad中的初始化工作
- function
initLocalStorage(){ -
(window.localStorage) { -
textarea.addEventListener( function() { -
window.localStorage[ = this.value; -
window.localStorage[ = newDate().getTime(); -
}, -
} { -
alert( are );not supported in this browser." -
} - }
-
- window.onload
= function(){ -
initDatabase(); -
initLocalStorage(); - }
● HTML5地理位置服务在Android中的应用Android中
- //启用地理定位
- webSettings.setGeolocationEnabled(true);
- //设置定位的数据库路径
- webSettings.setGeolocationDatabasePa
th(dir); -
- //配置权限(同样在WebChromeClient中实现)
- public
void onGeolocationPermissions ShowPrompt(String origin, -
GeolocationPermissions.Callback callback) { -
callback.invoke(origin, false); -
ShowPrompt(origin, callback); - }
在Manifest中添加权限
- <uses-permission
android:name="android.permission.ACCESS_FINE_LOCATION" /> - <uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
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() { -
(navigator.geolocation) { -
navigator.geolocation.getCurrentPosition(show_map,handle_error,{enableHighAccuracy: -
} { -
alert( browser );does not support HTML5 geoLocation" -
} - }
-
- function
show_map(position) { -
latitude = position.coords.latitude; -
longitude = position.coords.longitude; -
city = position.coords.city; -
localhost 5554 -
fix -82.411629 28.054553 -
fix -121.45356 46.51119 4392 -
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( -
document.getElementByIdx_x_x_x( -
document.getElementByIdx_x_x_x( - }
-
- function
handle_error(err) { -
(err.code) { -
1: -
alert( denied" ); -
-
2: -
alert( network );is down or the position satellites can't be contacted" -
-
3: -
alert( out" ); -
-
-
alert( error" ); -
-
} - }
其中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标签中声明 <html manifest="clock.manifest"> HTML5离线应用更新缓存机制分为手动更新和自动更新2种自动更新:在cache manifest文件本身发生变化时更新缓存 资源文件发生变化不会触发更新手动更新:使用window.applicationCache
- if
(window.applicationCache.status == window.applicationCache.UPDATEREADY) { -
window.applicationCache.update(); - }
在线状态检测HTML5 提供了两种检测是否在线的方式:navigator.online(true/false) 和 online/offline事件。在Android中构建离线应用
- //开启应用程序缓存
- webSettingssetAppCacheEn
abled( 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, -
totalUsedQuota, WebStorage.QuotaUpdater quotaUpdater) { -
quotaUpdater.updateQuota(spaceNeeded * - }
- android-HTML5开发android
- html5开发android应用
- 利用HTML5开发Android
- 利用HTML5开发Android
- Android HTML5 开发
- 利用HTML5开发Android
- 利用HTML5开发Android
- 利用HTML5开发Android
- 使用HTML5开发Android
- HTML5开发Android
- 利用HTML5开发Android
- Android开发HTML5应用
- 用HTML5开发Android
- 利用HTML5开发Android
- 利用HTML5开发Android
- 利用html5开发android
- Android开发&HTML5+App
- HTML5开发Android程序
- hdu4528小明系列故事——捉迷藏(bfs)
- Linux的shell中echo改变输出显示样式
- android组件-Intent
- UIImagePickerController 图像选取器--在iPhone中调用照相机、照片库
- Ubuntu 13.04下安装MariaDB 5.5
- Android HTML5 开发
- hdu 1878(欧拉回路)
- 变量、指针变量、指针数组、数组指针、函数指针、函数指针数组
- Python打印log,包括行号,路径,方法名,文件
- 模拟器不能上网的问题
- Pygame学习(2)------AI(人工智能)
- 每日一题(45) - 数组中的逆序对
- linux __attribute__ 分析
- trustzone调研