JS从Java返回结果

时间:2014-10-16 01:12:53

标签: javascript android cordova adt zeroconf

我正在尝试使用以下plugin,但在访问JS中的JAVA结果时遇到问题。

以下是与插件相关的简短版本

Java:

public void sendCallback(String action, ServiceInfo info) {
    JSONObject status = new JSONObject();
    try {
        status.put("action", action);
        status.put("service", jsonifyService(info));
        Log.d("ZeroConf", "Sending result: " + status.toString());
        PluginResult result = new PluginResult(PluginResult.Status.OK,
                status);
        result.setKeepCallback(true);
        this.callback.sendPluginResult(result);
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

JS

var ZeroConf = {
watch: function (type, callback) {
    return exec(function (result) {
        if (callback) {
            callback(result);
        }

    }, ZeroConf.fail, "ZeroConf", "watch", [type]);
}};module.exports = ZeroConf;

在我的html文件中,我试图显示结果,但没有任何工作!我对JAVA不是很熟悉,所以我不确定我的问题来源。

示例HTML文件:

var app = {
// Application Constructor
initialize: function() {
    this.bindEvents();
},
bindEvents: function() {
    document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
    app.receivedEvent('deviceready');
    ZeroConf.watch('_http._tcp.local.', function(result) {

这是我不知道如何从JAVA

访问结果的地方
 alert(result)
       // do something with the result


    });
},
receivedEvent: function(id) {
    var parentElement = document.getElementById(id);
    var listeningElement = parentElement.querySelector('.listening');
    var receivedElement = parentElement.querySelector('.received');
    listeningElement.setAttribute('style', 'display:none;');
    receivedElement.setAttribute('style', 'display:block;');
    console.log('Received Event: ' + id);
}};

注意:我确定它正常工作,因为我可以看到JAVA方面的结果“Log.d”

1 个答案:

答案 0 :(得分:0)

结果是object。您需要解析它或对其进行字符串化,具体取决于您要对其执行的操作。

onDeviceReady: function() {
    app.receivedEvent('deviceready');
    ZeroConf.watch('_http._tcp.local.', function(result) {
        // Stringify the result to display it all as a string
        resultText = JSON.stringify(result);
        alert(resultText);

        // just display some values from the object
        // for example PORT and NAME
        alert("port: "+result.service.port + ", name: "+result.service.name);

    });
},

结果对象结构在plugin's page

中描述