如何从phonegap中的java插件调用Javascript函数?

时间:2015-12-30 10:31:42

标签: javascript android jquery cordova phonegap-plugins

我正在为Phonegap应用程序开发语音识别android插件。我实际上是Phonegap的新手。以下是我的Java代码中的重要部分。从这段代码中,我需要调用Javascript函数test

public class CoolPlugin extends CordovaPlugin {

public static final String TAG = "Cool Plugin";
private SpeechRecognizer speech = null;
private Intent recognizerIntent;
private String LOG_TAG = "VoiceRecognitionActivity";
private List<String> previousInterim;

private List<String>adapterList = new ArrayList<String>();



private static final String INITIALIZE = "init";
private static final String PLAY = "play";
private static final String STOP = "stop";


private AudioManager mAudioManager;
private int mStreamVolume = 0;
private Context context;



public boolean execute(final String action, JSONArray args, final CallbackContext callbackContext) throws JSONException
{


   if(PLAY.equals(action))
    {
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {
                play(callbackContext);

            }
            });
    }
    return true;
}



public void play(CallbackContext callbackContext)
{

    //Start listening
    speech.stopListening();
    speech.cancel();
    speech.destroy();
    createRecog();
    speech.startListening(recognizerIntent);
    //adapter.clear();
}





private class RecognitionListenerClass implements RecognitionListener
{
    CallbackContext callbackContext;

    void onStartOfSpeechTimeout(CallbackContext callbackContext)
    {
        this.callbackContext = callbackContext;
    };


    @Override
    public void onPartialResults(Bundle arg0) {
        Log.i(LOG_TAG, "onPartialResults");
        final ArrayList<String> matches = arg0.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
        final float[] scores = arg0.getFloatArray(SpeechRecognizer.CONFIDENCE_SCORES);
        receiveWhatWasHeard(matches, scores);


    }

}



private void receiveWhatWasHeard(ArrayList<String> matches, float[] scores) 
{

    //CALL THE JAVASCRIPT FUNCTION!!
}


}

从方法receiveWhatWasHeard,我需要调用一个javascript函数。由于这是一个语音应用程序,请注意,每次听到此消息时都会调用此调用。

以下是我的JavaScript代码的一部分..

    var exec = require('cordova/exec');

function CoolPlugin() { 
 console.log("CoolPlugin.js: is created");
}



CoolPlugin.prototype.startRecognition = function(){
     console.log("CoolPlugin.js: showToast");

     exec(function(result){
         /*alert("OK" + reply);*/
       },
      function(result){
        /*alert("Error" + reply);*/
       },"CoolPlugin","play",[]);
    }



CoolPlugin.prototype.test = function(){
 //Do something and return information
}


 var coolPlugin = new CoolPlugin();
 module.exports = coolPlugin;

无需说大多数的手机教程都已经过时了,过去几天我一直在努力解决这个问题。有关如何将此Java实现为Javascript回调的任何想法吗?

0 个答案:

没有答案