webView與js互動——獲取通訊錄手機號並顯示運營商

上善若水發表於2016-07-19

今天,我整理下webView與js互動的方法。通過點選按鈕獲取手機通訊錄中的號碼,並回顯出手機號的運營商。

也是,抽上班時間寫的部落格,廢話就不多說了。直接上程式碼,程式碼能說明一切,相信有基礎的都能看懂。

工程目錄:


js_java_interaction.html

<html>
<body>
<input type="text" name="phoneNum" id="phoneNum" placeholder="請輸入或選擇手機號碼" style="height:30px;">
<input type="button" value="選擇" onclick="getPhoneNum()"><br/>
<label id="phoneType" name="phoneType"></label>
</body>
<script type="text/javascript">
        function getPhoneNum(){
            //通過js呼叫java程式碼
            window.control.getPhoneNumAndroid();
        }
        function retPhoneToJs(data){
            document.getElementById("phoneNum").value=data;

            var isChinaMobile = /^134[0-8]\d{7}$|^(?:13[5-9]|147|15[0-27-9]|178|18[2-478])\d{8}$/; //移動
         var isChinaUnion = /^(?:13[0-2]|145|15[56]|176|18[56])\d{8}$/; //聯通
         var isChinaTelcom = /^(?:133|153|177|18[019])\d{8}$/;//電信
         if(isChinaMobile.test(data)){
            document.getElementById("phoneType").innerHTML="中國移動";
         }else if(isChinaUnion.test(data)){
            document.getElementById("phoneType").innerHTML="中國聯通";
         }else if(isChinaTelcom.test(data)){
            document.getElementById("phoneType").innerHTML="中國電信";
         }
        }
</script>
</html>
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <WebView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/id_mwebview"/>
</RelativeLayout>
MainActivity.java

package com.csii.wj;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class MainActivity extends AppCompatActivity {
    private  WebView mWebView;
    private String phoneNo;//通訊錄電話號碼
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    Intent intent = new Intent(Intent.ACTION_PICK,
                            ContactsContract.Contacts.CONTENT_URI);
                    startActivityForResult(intent, 100);
                    break;
            }
        }
    };

    @SuppressLint("JavascriptInterface")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //獲得WebView控制元件
        mWebView = (WebView) findViewById(R.id.id_mwebview);
        //得到WebView控制元件的設定物件 WebSettings
        WebSettings settings = mWebView.getSettings();
        //可識別js程式碼
        settings.setJavaScriptEnabled(true);
        //新增js介面
        mWebView.addJavascriptInterface(new JSInteraction(), "control");
        mWebView.setWebChromeClient(new WebChromeClient() {
        });
        mWebView.setWebViewClient(new WebViewClient() {
        });
        mWebView.loadUrl("file:///android_asset/js_java_interaction.html");
    }

    //Interaction:相互作用
    public class JSInteraction {
        @JavascriptInterface
        public void getPhoneNumAndroid() {
            Message msg = Message.obtain();
            msg.what = 0;
            mHandler.sendMessage(msg);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100) {
            if (data != null) {
                Uri contactData = data.getData();
                Cursor c = managedQuery(contactData, null, null, null, null);
                if (c.moveToFirst()) {
                    String name = getContactPhone(c);
                    phoneNo = name;
                }
                //通過java程式碼嗲用js方法
                mWebView.loadUrl("javascript:retPhoneToJs(\""+phoneNo+"\")");
            }
        }
    }

    // 獲取聯絡人電話
    private String getContactPhone(Cursor cursor) {
        int phoneColumn = cursor
                .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER);
        int phoneNum = cursor.getInt(phoneColumn);
        String phoneResult = "";
        if (phoneNum > 0) {
            // 獲得聯絡人的ID號
            int idColumn = cursor.getColumnIndex(ContactsContract.Contacts._ID);
            String contactId = cursor.getString(idColumn);
            // 獲得聯絡人的電話號碼的cursor;
            Cursor phones = getContentResolver().query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = "
                            + contactId, null, null);
            if (phones.moveToFirst()) {
                // 遍歷所有的電話號碼
                for (; !phones.isAfterLast(); phones.moveToNext()) {
                    int index = phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
                    int typeindex = phones
                            .getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
                    int phone_type = phones.getInt(typeindex);
                    String phoneNumber = phones.getString(index);
                    switch (phone_type) {
                        case 2:
                            phoneResult = phoneNumber;
                            break;
                    }
                }
                if (!phones.isClosed()) {
                    phones.close();
                }
            }
        }
        return phoneResult;
    }
}
最後千萬不要忘記在清單檔案中加入獲取通訊錄聯絡人的許可權:

<uses-permission android:name="android.permission.READ_CONTACTS" />
OK,到此為止程式碼就貼完了。順利實現了我們想要的效果。





相關文章