Phonegap 获取手机设备信息 IMEI

phonegap的Device 提供有:

device.model :返回设备的模型或产品的名称

device.cordova :返回cordova的版本

device.uuid :返回手机 uuid

device.version :返回系统版本

device.platform :返回手机的平台信息 (android/ios 等等)

唯独没有Imei 的获取方法

本节在phonegap提供的插件上 增加一个imei的获取

Device调用方法参考 http://blog.csdn.net/aaawqqq/article/details/21169587

<1> 在控制台 创建一个phonegap工程 命令如下

 phonegap create my-app cd my-app phonegap run android

<2> 我们从命令行进入 到工程目录下的 plugins文件夹

cd my-appcd plugins

<3> 现在开始下载插件

cordova plugin add org.apache.cordova.device

<4> 添加android 平台工程 (ios把 "android" 替换)

cordova platform add android


<5> 编译android工程

cordova build

至此 devices 已经生成...

现在大家只需要将工程导入到eclipse当中 使用官方APi语句在javascript中调用


要获取imei 需要改动 原生的Device 2个地方

第一个是 assets 目录下 www/plugins 里面的org.apache.cordova.device / device.js

cordova.define("org.apache.cordova.device.device", function(require, exports, module) { /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements.  See the NOTICE file * distributed with this work for additional information * regarding copyright ownership.  The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License.  You may obtain a copy of the License at * *   http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied.  See the License for the * specific language governing permissions and limitations * under the License. **/var argscheck = require('cordova/argscheck'),    channel = require('cordova/channel'),    utils = require('cordova/utils'),    exec = require('cordova/exec'),    cordova = require('cordova');channel.createSticky('onCordovaInfoReady');// Tell cordova channel to wait on the CordovaInfoReady eventchannel.waitForInitialization('onCordovaInfoReady');/** * This represents the mobile device, and provides properties for inspecting the model, version, UUID of the * phone, etc. * @constructor */function Device() {    this.available = false;    this.platform = null;    this.version = null;    this.uuid = null;    this.cordova = null;    this.model = null;    //添加imei    this.imei = null;    var me = this;    channel.onCordovaReady.subscribe(function() {        me.getInfo(function(info) {            //ignoring info.cordova returning from native, we should use value from cordova.version defined in cordova.js            //TODO: CB-5105 native implementations should not return info.cordova            var buildLabel = cordova.version;            me.available = true;            me.platform = info.platform;            me.version = info.version;            me.uuid = info.uuid;            me.cordova = buildLabel;            me.model = info.model;            //添加imei            me.imei = info.imei;            channel.onCordovaInfoReady.fire();        },function(e) {            me.available = false;            utils.alert("[ERROR] Error initializing Cordova: " + e);        });    });}/** * Get device info * * @param {Function} successCallback The function to call when the heading data is available * @param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL) */Device.prototype.getInfo = function(successCallback, errorCallback) {    argscheck.checkArgs('fF', 'Device.getInfo', arguments);    exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);};module.exports = new Device();});


第二个是 在 src 当中 修改device类

/*       Licensed to the Apache Software Foundation (ASF) under one       or more contributor license agreements.  See the NOTICE file       distributed with this work for additional information       regarding copyright ownership.  The ASF licenses this file       to you under the Apache License, Version 2.0 (the       "License"); you may not use this file except in compliance       with the License.  You may obtain a copy of the License at         http://www.apache.org/licenses/LICENSE-2.0       Unless required by applicable law or agreed to in writing,       software distributed under the License is distributed on an       "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       KIND, either express or implied.  See the License for the       specific language governing permissions and limitations       under the License.*/package org.apache.cordova.device;import java.util.TimeZone;import org.apache.cordova.CallbackContext;import org.apache.cordova.CordovaInterface;import org.apache.cordova.CordovaPlugin;import org.apache.cordova.CordovaWebView;import org.json.JSONArray;import org.json.JSONException;import org.json.JSONObject;import android.content.Context;import android.provider.Settings;import android.telephony.TelephonyManager;import android.util.Log;public class Device extends CordovaPlugin {    public static final String TAG = "Device";    public static String cordovaVersion = "dev";              // Cordova version    public static String platform;                            // Device OS    public static String uuid;                                // Device UUID    private static final String ANDROID_PLATFORM = "Android";    private static final String AMAZON_PLATFORM = "amazon-fireos";    private static final String AMAZON_DEVICE = "Amazon";    /**     * Constructor.     */    public Device() {    }    /**     * Sets the context of the Command. This can then be used to do things like     * get file paths associated with the Activity.     *     * @param cordova The context of the main Activity.     * @param webView The CordovaWebView Cordova is running in.     */    public void initialize(CordovaInterface cordova, CordovaWebView webView) {        super.initialize(cordova, webView);        Device.uuid = getUuid();    }    /**     * Executes the request and returns PluginResult.     *     * @param action            The action to execute.     * @param args              JSONArry of arguments for the plugin.     * @param callbackContext   The callback id used when calling back into JavaScript.     * @return                  True if the action was valid, false if not.     */    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {        if (action.equals("getDeviceInfo")) {            JSONObject r = new JSONObject();            r.put("uuid", Device.uuid);            r.put("version", this.getOSVersion());            r.put("platform", this.getPlatform());            r.put("cordova", Device.cordovaVersion);            r.put("model", this.getModel());            //添加imei 的返回值            r.put("imei", this.imei());            callbackContext.success(r);        }        else {            return false;        }        return true;    }    //--------------------------------------------------------------------------    // LOCAL METHODS    //--------------------------------------------------------------------------        // 获取本地Imei号码     private String imei() {//    String Imei = ((TelephonyManager) cordova.getActivity().getSystemService(cordova.getActivity().TELEPHONY_SERVICE))//    .getDeviceId();//return Imei;           TelephonyManager systemService = (TelephonyManager)cordova.getActivity().getSystemService(Context.TELEPHONY_SERVICE);       String deviceId = systemService.getDeviceId();       Log.i("123", deviceId);       return systemService.getDeviceId();}/**     * Get the OS name.     *      * @return     */    public String getPlatform() {        String platform;        if (isAmazonDevice()) {            platform = AMAZON_PLATFORM;        } else {            platform = ANDROID_PLATFORM;        }        return platform;    }    /**     * Get the device's Universally Unique Identifier (UUID).     *     * @return     */    public String getUuid() {        String uuid = Settings.Secure.getString(this.cordova.getActivity().getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);        return uuid;    }    /**     * Get the Cordova version.     *     * @return     */    public String getCordovaVersion() {        return Device.cordovaVersion;    }    public String getModel() {        String model = android.os.Build.MODEL;        return model;    }    public String getProductName() {        String productname = android.os.Build.PRODUCT;        return productname;    }    /**     * Get the OS version.     *     * @return     */    public String getOSVersion() {        String osversion = android.os.Build.VERSION.RELEASE;        return osversion;    }    public String getSDKVersion() {        @SuppressWarnings("deprecation")        String sdkversion = android.os.Build.VERSION.SDK;        return sdkversion;    }    public String getTimeZoneID() {        TimeZone tz = TimeZone.getDefault();        return (tz.getID());    }    /**     * Function to check if the device is manufactured by Amazon     *      * @return     */    public boolean isAmazonDevice() {        if (android.os.Build.MANUFACTURER.equals(AMAZON_DEVICE)) {            return true;        }        return false;    }}


最后 在androidmanifest.xml 当中 添加权限

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

这是 获取imei必要的权限

修改完成!

将下方语句考到 assets目录下 www/index.html 当中 完全复制过去;

<!DOCTYPE html><html>   <head>      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Contact Example</title>     <script type="text/javascript" charset="utf-8" src="cordova.js"></script>   <script type="text/javascript" charset="utf-8">            // Wait for device API libraries to load          // document.addEventListener("deviceready", onDeviceReady, false);          // device APIs are available      function onDeviceReady() {          // Wait for device API libraries to load    //                           //var element = document.getElementById('deviceProperties');                   //alert(element);                       // element.innerHTML =             // 'Device Model: '    + device.model    + '<br />' +              // 'Device Cordova: '  + device.cordova  + '<br />' +                // 'Device Platform: ' + device.platform + '<br />' +                                        // 'Device UUID: '     + device.uuid     + '<br />' +                                        // 'Device Version: '  + device.version  + '<br />';                alert( device.model +"----"+device.cordova +"------"+ device.uuid +"-----"+device.version+"----"+device.platform );        }        function baozi(){ alert("S1");}        function intent() {       onDeviceReady();     }          </script>       </head>       <body>          <h1>Example</h1>         <p>Find Contacts</p>        <p><a href="#" onclick="baozi(); return false;">Vibrate</a></p>       <p><a href="#" onclick="intent(); return false;">Html跳转到android界面</a></p>      </body>   </html>

点击 " Html跳转到android界面 " 就会弹出 alert 如下:

依次

device.model :返回设备的模型或产品的名称

device.cordova :返回cordova的版本

device.uuid :返回手机 uuid

device.version :返回系统版本

device.platform :返回手机的平台信息 (android/ios 等等)

第六个参数就是 Imei号码

工程下载 将phonegap的platforms导入到eclipse中

如果报错clear一下 查看导的lib包 有没有报错

如果还有错 那么就是您选用了 google的API 改成最新版的android API 就好了

如果导入工程遇到问题 可以查阅我此篇文章

Blog: http://blog.csdn.net/aaawqqq/article/details/20463183

Phonegap解决错误:Error initializing Cordova:Class not found:

http://blog.csdn.net/aaawqqq/article/details/21243869

本Demo下载:http://download.csdn.net/detail/aaawqqq/7035095

下篇写 phonegap获取联系人

更多相关文章

  1. Android获取外部和内部存储空间总大小
  2. Android(安卓)GPS定位实现
  3. 一个简单的Android小实例
  4. 获取Android手机上的图片和视频缩略图
  5. 下载 android source 之repo获取
  6. Android(安卓)View框架总结(八)ViewGroup事件分发机制
  7. android 巧用finish方法
  8. android:Bitmap和Drawable相互转换方法
  9. Android(安卓)获取手机的厂商、型号、Android系统版本号、IMEI、

随机推荐

  1. android软键盘上添加一个按钮
  2. 最全面的AndroidStudio配置指南总结-包括
  3. 移动端键盘弹起引起的fixed定位问题
  4. Android(安卓)ViewDragHelper实现窗帘效
  5. 微软:Android(安卓)智能手机正在被僵尸网
  6. Android(安卓)Pay,能冲破第三方支付围堵
  7. Android内存泄漏检测及修复(转载)
  8. iOS 开发者的 Android(安卓)第一课
  9. Android、iOS和Windows Phone中的推送技
  10. Android--播放Gif的取巧办法