MainActivity のネイティブ メソッドを使用して、phonegap の index.html から電話をかけようとしています。
phonegap 3.0 と android 4.3 プラットフォームを使用しています。この投稿で2 番目の回答を試しましたが、このバージョンでは機能しません。
これを乗り越えるための最良のアプローチは何ですか?
カスタム プラグインを作成して、ネイティブ側から任意のメソッドを呼び出すことができます。別の JavaScript ファイル (customplugin.js など) を作成し、これをその中に入れます。
var CustomPlugin = {};
CustomPlugin.callNativeMethod = function() {
cordova.exec(null, null, "CustomPlugin", "callNativeMethod", []);
};
ネイティブ Java 側で、新しいクラスを作成し、CustomPlugin.java という名前を付けて、これを追加します。
package com.yourpackage;
import org.apache.cordova.CordovaWebView;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaInterface;
import org.apache.cordova.api.CordovaPlugin;
import com.yourpackage.MainActivity;
public class CustomPlugin extends CordovaPlugin
{
private static final String TAG = "CustomPlugin";
private CallbackContext callbackContext = null;
private MainActivity activity = null;
/**
* Override the plugin initialise method and set the Activity as an
* instance variable.
*/
@Override
public void initialize(CordovaInterface cordova, CordovaWebView webView)
{
super.initialize(cordova, webView);
// Set the Activity.
this.activity = (MainActivity) cordova.getActivity();
}
/**
* Here you can delegate any JavaScript methods. The "action" argument will contain the
* name of the delegated method and the "args" will contain any arguments passed from the
* JavaScript method.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException
{
this.callbackContext = callbackContext;
Log.d(TAG, callbackContext.getCallbackId() + ": " + action);
if (action.equals("callNativeMethod"))
{
this.callNativeMethod();
}
else
{
return false;
}
return true;
}
private void callNativeMethod()
{
// Here we simply call the method from the Activity.
this.activity.callActivityMethod();
}
}
次の行を追加して、config.xml ファイルにプラグインをマッピングしてください。
...
<feature name="CustomPlugin">
<param name="android-package" value="com.yourpackage.CustomPlugin" />
</feature>
...
index.html からプラグインを呼び出すには、JavaScript メソッドを呼び出すだけです。
CustomPlugin.callNativeMethod();
このメソッドを使用すると、多くのカスタム メソッドを簡単に設定できます。詳細については、こちらの PhoneGap プラグイン開発ガイドを確認してください。