简体   繁体   English

如何在Java函数返回之前等待某个回调方法被调用?

[英]how to wait for a certain callback method to be called before a function returns in java?

I am writing a phonegap plugin.My code outline is this 我正在编写一个phonegap插件。我的代码概述是这样

public PluginResult execute(String action, JSONArray arg1, String arg2) {
      try{
        if (action.equals("authenticate")) {
           this.startlogin();
           return new PluginResult(PluginResult.Status.OK);
        }
        else {
            return new PluginResult(PluginResult.Status.INVALID_ACTION);
        }
       }catch(Exception e){}
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION); 

    }

startlogin() method calls a function which has callback method registered which gets called after certain event.ie startlogin() method returns but a certain method is called after an event occurs which is asynchronous. startlogin()方法调用一个注册了回调方法的函数,该函数在某些事件后被调用。即,startlogin()方法返回,但在异步事件发生后调用某个方法。

 public void startlogin(){

    login();//this has callback method
 }

how to wait until that callback method is finished before i return from execute method? 如何从我的execute方法返回之前等待该回调方法完成? Whats the best method in java? 什么是Java中最好的方法?

PS:I cannot change execute method prototype since phonegap plugin works on execute method. PS:我无法更改执行方法原型,因为phonegap插件适用于执行方法。

Easiest approach: 最简单的方法:

if (this.startlogin()) ...

...

public boolean startlogin(){

    return login();
}

It seems to me that you're trying to mix synchronous with asynchronous... 在我看来,您正在尝试将同步与异步混合在一起...

What you should really do is have the callback method return the PluginResult. 您真正应该做的是让回调方法返回PluginResult。

Cheers, 干杯,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在用RxJava调用另一个方法之前等待 - How to wait before another method is called with RxJava 如何等待结果回调完成后再继续(Android)? - How to wait for a method with result callback to complete before continuing (Android)? Java SpringBoot:CRUD方法在调用服务完成之前返回值 - Java SpringBoot: CRUD method returns value before called Service finishes 如何编写从服务器端 JavaScript 调用的 Java 方法,该方法将 JS 回调函数作为参数? - How do I write a Java method, to be called from server side JavaScript, that takes a JS callback function as an argument? 在从Java中的方法返回之前需要等待异步api回调 - Need to wait for asynchronous api callback before I return from method in Java Java notify() 在 wait() 之前被调用 - Java notify() gets called before wait() 如何创建一个在Java中接受回调函数的方法? - How to create a method that accepts a callback function in java? 如何使Java等待方法完成才能继续? - How do I make Java wait for a method to finish before continuing? 如何在继续循环之前等待回调完成? - How to wait for callback to finish before continuing the loop? Java:在调用其他函数之前是否可以始终执行某个函数? (比如JUnit中的@Before) - Java: Is it possible to always execute a certain function before other functions are called? (Like @Before in JUnit)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM