如何使用phonegap获取wifi路由器的ssid?

时间:2014-07-02 10:07:32

标签: android cordova cordova-plugins

我正在使用phonegap和java开发一个Android移动应用程序。我的要求是捕获wifi路由器的ssid并将其存储到数据库中。

无论如何都要捕获 ssid

提前致谢。

1 个答案:

答案 0 :(得分:3)

请尝试以下(仅适用于Android)。将以下类添加到src文件夹

WifiInfoPlugin.class:

package com.example.getmac;

import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;
import android.webkit.WebSettings.PluginState;

public class WifiInfoPlugin extends CordovaPlugin {
    public static final String SSID_NAME = "WifiInfo";

    @Override
    public boolean execute(String action, JSONArray args,
            CallbackContext callbackContext) throws JSONException {
        if (SSID_NAME.equals(action)) {
            String wifiInfo = this.getWifiInfo();
            Log.e("Wifi SSID", wifiInfo);
            if(wifiInfo != ""){
                JSONObject jsonResult = new JSONObject();
            try {
                    jsonResult.put("Wifi SSID", wifiInfo);
                    PluginResult r= new PluginResult(PluginResult.Status.OK,jsonResult);
                    callbackContext.success(wifiInfo);
                    r.setKeepCallback(true);
                    return true;

            } catch (JSONException e) {
                PluginResult r = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
                callbackContext.error("error");
                r.setKeepCallback(true);
                callbackContext.sendPluginResult(r);
                return true;
            }
        }
        }
        return false;
    }

    private String getWifiInfo() {

        WifiManager manager = (WifiManager)this.cordova.getActivity().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = manager.getConnectionInfo();
        //String address = info.getMacAddress();
        String address = info.getSSID ();
        Log.e("ssid address", address);
        return address;
    }

}
之后在index.html脚本中的

就像:

document.addEventListener("deviceready",onDeviceReady,false);

function onDeviceReady(){
     var success = function(result) { alert("The SSID is " + result); };
     var error = function(message) { alert("Oopsie! " + message); };
     WifiInfo.createEvent(success,error);
}

然后创建getWifiInfoFromPLT.js就像在索引页中包含这个js

var WifiInfo = {

createEvent : function(successCallback, failureCallback) {
    cordova.exec(successCallback, failureCallback, 'WifiInfoPlugin',
            'WifiInfo', []);
}
};

res/xml/cofig.xml文件夹

中添加以下内容
 <feature name="WifiInfoPlugin" >
    <param
        name="android-package"
        value="com.example.getWifiInfo.WifiInfoPlugin" >
    </param>
</feature>

并添加necessary permissons in your manifest。让我知道任何困难

示例输出: enter image description here