1、为确保有权限访问网页,在AndroidManifest.xml里面添加代码如下:
<uses-permission android:name="android.permission.INTERNET"/>
2、在res/layout/main.xml里添加
<WebView android:layout_height="fill_parent" android:layout_width="fill_parent" android:id="@+id/webview" />
3、activity 里面添加
1 package com.phoneplus; 2 import android.app.Activity; 3 import android.content.Intent; 4 import android.os.Build; 5 import android.os.Bundle; 6 import android.util.DisplayMetrics; 7 import android.util.Log; 8 import android.webkit.JsResult; 9 import android.webkit.WebChromeClient; 10 import android.webkit.WebSettings; 11 import android.webkit.WebView; 12 import android.widget.Toast; 13 14 public class DemoActivity extends Activity { 15 WebView webView; 16 String url = "http://10.254.58.32/demo/gradeplan/activitydetail.php?v=1"; 17 private WebSettings settings; 18 19 /** Called when the activity is first created. */ 20 @Override 21 public void onCreate(Bundle savedInstanceState) { 22 super.onCreate(savedInstanceState); 23 setContentView(R.layout.main); 24 //测试WebView 25 webView = (WebView) findViewById(R.id.webview); 26 webView.getSettings().setSavePassword(false); 27 webView.getSettings().setJavaScriptEnabled(true); 28 webView.getSettings().setUseWideViewPort(true); 29 webView.getSettings().setLoadWithOverviewMode(true); 30 webView.getSettings().setBuiltInZoomControls(true); 31 webView.getSettings().setSupportZoom(true); 32 display(webView); 33 //显示网页 34 webHtml(url); 35 webView.setWebChromeClient(new MyWebChromeClient()); 36 } 37 38 class MyWebChromeClient extends WebChromeClient{ 39 @Override 40 public boolean onJsAlert(WebView view, String url, String message, JsResult result){ 41 42 Log.d("==message==",message); 43 Log.d("==url==",url); 44 Log.d("==JsResult==",result.toString()); 45 46 result.confirm(); 47 return true; 48 } 49 50 } 51 52 /** 直接网页显示 */ 53 private void webHtml(String url) { 54 try { 55 webView.loadUrl(url); 56 } catch (Exception ex) { 57 ex.printStackTrace(); 58 } 59 } 60 61 /** 62 * 分辨率自适应 63 * @param webView 64 */ 65 private void display(WebView webView){ 66 DisplayMetrics dm = new DisplayMetrics(); 67 getWindowManager().getDefaultDisplay().getMetrics(dm); 68 int width = (int) (dm.widthPixels * dm.density); 69 70 if ( Build.VERSION.SDK_INT >= 14 && width >= 480 ) { 71 webView.setInitialScale(100); 72 }else if ( Build.VERSION.SDK_INT ==14 && width >= 320 ) { 73 webView.setInitialScale(67); 74 }else if ( Build.VERSION.SDK_INT == 14 && width < 320 ) { 75 webView.setInitialScale(50); 76 }else { 77 webView.setInitialScale(1); 78 } 79 } 80 }
4、HTML里面
1 <script type="text/javascript"> 2 3 function get_activity(str_flag){ 4 <?php 5 //android 6 if( $_GET['v'] == '1'){ 7 echo 'alert(str_flag); '; 8 } 9 //ios 10 else { 11 echo 'document.location = str_flag;'; 12 } 13 ?> 14 } 15 </script>