android和js的相互调用

使用html开发android会是一个流行的趋势,至少现在就有很多公司在android中使用了,我们这些js学的不怎么好的更不能落伍了:


android和js的相互调用
 

android查询通话记录后调用js显示   android调js  点击拍照可将图片替换成拍照的图片

 js调用android的Toast    js调android

布局文件: 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
         >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <WebView
                android:id="@+id/webView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />
        </LinearLayout>
    </ScrollView>

</RelativeLayout>

html代码:

<meta http-equiv="Content-Type" content="text/html; charset=GBK">
<html>

<head>
      <title>android调用js和js调用android</title>
     <script type="text/javascript">  
            function show(jsondata){              
                    var jsonobjs = eval(jsondata);  
                    var table = document.getElementById("personTable");  
                    for(var y=0; y<jsonobjs.length; y++){  
                        var tr = table.insertRow(table.rows.length);   
                        var td1 = tr.insertCell(0);  
                        var td2 = tr.insertCell(1);  
                        td2.align = "center";  
                        var td3 = tr.insertCell(2);  
                        td3.align = "center";  
                        td1.innerHTML = jsonobjs[y].name;   
                        td2.innerHTML = jsonobjs[y].amount;   
                        td3.innerHTML = "<a href='javascript:contact.call(\""+ jsonobjs[y].phone+ "\")'>"+ jsonobjs[y].phone+ "</a>";   
                    }  
            }  
            
            function funImgSrc(dateImg){
            document.getElementById("imgSrc").src=dateImg;
            }
            
        </script>  
        
       <style type="text/css">
       #car{
        width="30px" ;
        height="50px"
       }
       </style>
      
</head>
<body onload="javascript:contact.showcontacts()">
   第一次调用html页面
   <button id="btn" onClick="javascript:contact.toast('123')">你好</button>
   <table  border="0" width="100%" id="personTable" cellspacing="0">
		<tr>  
                <td width="30%" align="center">存款</td>  
                <td align="center">电话</td>  
           </tr>  
  
</table>   
<br/>
<button  id="car"  onClick="javascript:contact.Carmeps()">点击拍照将下面的图片换掉</button>
<br/>
<img id="imgSrc" src="http://img.ycwb.com/news/attachement/jpg/site2/20120904/001e90704bd511affd1840.jpg"  alt="上海鲜花港 - 郁金香"  />
</body>
</html>

操作的代码:加载本地的html代码

下面设计到的技术点有json的组装,WebView ,内容提供者,子线成和主线程的通信,android调用js,js调用android代码

public class MainActivity extends Activity {

	private WebView webView;
	private Handler handler;
	private List<user> listUser=null;

	@SuppressLint("SetJavaScriptEnabled")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.fragment_main);
		init();
		listUser= new ArrayList<MainActivity.user>();
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what==100){
					//System.out.println((String)msg.obj);
					if(listUser!=null&&listUser.size()>0){
						final JSONArray jsonArray = new JSONArray();
						for(int n=0;n<listUser.size();n++){
							user u=listUser.get(n);
							try{
					JSONObject jsonobj = new JSONObject();
					jsonobj.put("phone", u.getUserphone());
					jsonobj.put("name", u.getUsername());
							jsonobj.put("amount",u.getAcc());
							jsonArray.put(jsonobj);
							}catch(Exception e){
								e.printStackTrace();
							}
						}
				webView.loadUrl("javascript:show('" + jsonArray + "')");
						System.out.println(jsonArray);
					}
					
				}
			}
		};
	}

	@SuppressLint("JavascriptInterface")
	void init() {
		webView = (WebView) findViewById(R.id.webView);
		webView.requestFocus();
		WebSettings webSettings = webView.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setSupportZoom(true);
		webSettings.setDomStorageEnabled(true);
		// webSettings.setPluginState(true);
		webSettings.setUseWideViewPort(true);
		webSettings.setLoadWithOverviewMode(true);
		webSettings.setSupportZoom(true);
		webSettings.setBuiltInZoomControls(true);
		webSettings.setTextSize(WebSettings.TextSize.LARGER);//设置字体
	//	webSettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);//话说是设置适应屏幕,设置了不是想要的效果
		webView.addJavascriptInterface(new InJavaScriptLocalObj(), "contact");//创建调用js代码的桥梁
		// webView.loadUrl("http://www.baidu.com");
		// webView.loadUrl("file:///android_assets/indexfile/index.html");
		webView.loadUrl("file:///android_asset/index.html");
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();

		webView.setWebViewClient(new WebViewClient() {
		//使用WebView来访问html时,必须重写shouldOverrideUrlLoading方法
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}

		});
	}

	//通过@JavascriptInterface来创建js调用android代码和android调用js代码
	final class InJavaScriptLocalObj {
		@JavascriptInterface
		// JavaScript
		public void call(String phone) {
			 startActivity(new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +
			 phone)));
			Toast.makeText(MainActivity.this, "正在呼叫:"+phone, Toast.LENGTH_LONG).show();
		}

		// Html内容提供者查询数据后,将数据给js,js操作html显示数据
		public void showcontacts() {
			new Thread(new Runnable() {
				@Override
			public void run() {
			Cursor cursor = MainActivity.this.getContentResolver()
			.query(CallLog.Calls.CONTENT_URI,new String[] { CalLog.Calls.NUMBER,CallLog.Calls.CACHED_NAME, }, null,null, CallLog.Calls.DEFAULT_SORT_ORDER);
			while (cursor.moveToNext()) {
			
			user u = new user();
			if("".equals(cursor.getString(1))||null==cursor.getString(1)){
				u.setUsername("百合不是茶..");
					}else{
					u.setUsername(cursor.getString(1));
							}
							u.setUserphone(cursor.getString(0));
							u.setAcc(""+cursor.getColumnCount());
							listUser.add(u);
					}
					cursor.close();
					handler.sendEmptyMessage(100);
					  
				}
			}).start();
			
		}

		//js调用toast的代码格为:javascript:contact.toast("你好")
		public void toast(String str) {
		Toast.makeText(MainActivity.this, "js调用android的方法:  --- " + str,
					Toast.LENGTH_LONG).show();
		}
		
		//js调用其拍照
		public void Carmeps(){
		Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		 startActivityForResult(intent, 101); 
		}
		
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if(requestCode==101){
			Uri uri=data.getData();
			if(uri!=null){
		webView.loadUrl("javascript:funImgSrc('"+uri+"')");//android调用js修改图
			}
			
		}
	}

	// 锟斤拷锟截硷拷拇锟斤拷锟�
	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		// super.onBackPressed();
		if (webView != null && webView.canGoBack()) {
			webView.goBack();
		} else {
			MainActivity.this.finish();
		}
	}

	
	//由于需要在UI中将数据以json的形式给js,所以使用bean来操作
	class user{
		private String username;
		public String getUsername() {
			return username;
		}
		public void setUsername(String username) {
			this.username = username;
		}
		public String getUserphone() {
			return userphone;
		}
		public void setUserphone(String userphone) {
			this.userphone = userphone;
		}
		public String getAcc() {
			return acc;
		}
		public void setAcc(String acc) {
			this.acc = acc;
		}
		private String userphone;
		private String acc;
	}
}

注意申请权限

相关推荐