如何正确设置phonegap插件回调

时间:2012-09-30 09:58:48

标签: cordova jquery-mobile phonegap-plugins

您好我开发了一个手机间隙插件,以查看目录是否为空。

我使用以下代码

        public PluginResult execute(String arg0, final JSONArray arg1, String arg2) {

        if ( arg0.equals(SHOW6) )
        {

            PluginResult result = null;

                    File file = new File("/mnt/sdcard/koinoxrista/todesktop/");

                    if(file.isDirectory()){

                        if(file.list().length>0){

                        /*  Builder dialog = new AlertDialog.Builder(ctx);
                            dialog.setNegativeButton("Ok", null);
                            AlertDialog alert = dialog.create();
                            alert.setTitle("Failure");
                            alert.setMessage("Directory is not empty!");
                            alert.show();
                        */
                            return new PluginResult(Status.ERROR, "Directory is not empty!");
                        //  System.out.println("Directory is not empty!");

                        }else{

                        /*                      
                            Builder dialog = new AlertDialog.Builder(ctx);
                            dialog.setNegativeButton("Ok", null);
                            AlertDialog alert = dialog.create();
                            alert.setTitle("Failure");
                            alert.setMessage("Directory is empty!");
                            alert.show();
                        */       
                            return new PluginResult(Status.OK, "Directory is empty!");
                    //      System.out.println("Directory is empty!");

                        }

                    }else{

                //      System.out.println("This is not a directory");

                    }

        }

这就是我从js

中调用它的方式
var msgbox = function() {
};

msgbox.prototype.show6 = function(success, fail) {
    return PhoneGap.exec(success, fail, "msgbox", "show6", []);
    };  

function success(e){globalcreate = 0; alert(e);}
function fail(r){globalcreate = 1; alert(r);}

msgbox = new msgbox();

我想提醒目录是否为空。

如何设置回调?

如果我在.java上取消注释警告对话框,则会收到正确的结果。

1 个答案:

答案 0 :(得分:0)

看起来像是一个范围问题。将成功和失败方法声明为全局变量是一个坏主意。你想做这样的事情:

var msgbox = function() { 
};

msgbox.prototype.show6 = function(success, fail) {
    return PhoneGap.exec(success, fail, "msgbox", "show6", []);
};  

function showSuccess(e){globalcreate = 0; alert(e);}
function showFail(r){globalcreate = 1; alert(r);}

msgbox = new msgbox();

并称之为:

msgbox.show6(showSuccess, showFail);

或者你总是希望做同样的事情,你可以在你的方法中拉出它们:

msgbox.prototype.show6 = function() {
    var win = function(e){globalcreate = 0; alert(e);}
    var fail = function(r){globalcreate = 1; alert(r);}
    return PhoneGap.exec(win, fail, "msgbox", "show6", []);
};  

并称之为:

msgbox.show6();

您注释掉的Java代码应始终为run on the UI thread,如果您不这样做,则会导致问题。