调试它的最佳方法是使用 ADT(Android 开发者工具)。有很多小错误。这篇文章是一个非常有用的资源:http ://devgirl.org/2013/09/17/how-to-write-a-phonegap-3-0-plugin-for-android/
这是 sms.java 代码:
package com.adamwadeharris.sms;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.PendingIntent;
import android.content.Intent;
import android.telephony.SmsManager;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.PluginResult;
public class Sms extends CordovaPlugin {
public final String ACTION_SEND_SMS = "send";
@Override
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
if (action.equals(ACTION_SEND_SMS)) {
try {
String phoneNumber = args.getString(0);
String message = args.getString(1);
String method = args.getString(2);
if(method.equalsIgnoreCase("INTENT")){
invokeSMSIntent(phoneNumber, message);
callbackContext.sendPluginResult(new PluginResult( PluginResult.Status.NO_RESULT));
} else{
send(phoneNumber, message);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK));
return true;
}
catch (JSONException ex) {
callbackContext.sendPluginResult(new PluginResult( PluginResult.Status.JSON_EXCEPTION));
}
}
return false;
}
private void invokeSMSIntent(String phoneNumber, String message) {
Intent sendIntent = new Intent(Intent.ACTION_VIEW);
sendIntent.putExtra("sms_body", message);
sendIntent.putExtra("address", phoneNumber);
sendIntent.setType("vnd.android-dir/mms-sms");
this.cordova.getActivity().startActivity(sendIntent);
}
private void send(String phoneNumber, String message) {
SmsManager manager = SmsManager.getDefault();
PendingIntent sentIntent = PendingIntent.getActivity(this.cordova.getActivity(), 0, new Intent(), 0);
manager.sendTextMessage(phoneNumber, null, message, sentIntent, null);
}
}
这是 sms.js 代码:
var sms = {
send: function(phone, message, method, successCallback, failureCallback) {
cordova.exec(
successCallback,
failureCallback,
'Sms',
'send',
[phone, message, method]
);
}
}
module.exports = sms;
这是plugin.xml:
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
id="com.adamwadeharris.sms"
version="0.1.0">
<name>Sms</name>
<description>Cordova SMS Send Plugin</description>
<license>MIT</license>
<keywords>cordova,phonegap,sms</keywords>
<js-module src="www/sms.js" name="Sms">
<clobbers target="window.sms" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Sms">
<param name="android-package" value="com.adamwadeharris.sms.Sms"/>
</feature>
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.SEND_SMS" />
</config-file>
<source-file src="src/android/Sms.java" target-dir="src/com/adamwadeharris/sms" />
</platform>
</plugin>
编辑
另外,我在 github 上有可用的插件:https ://github.com/aharris88/phonegap-sms-plugin
编辑
此插件现已移至:
https ://github.com/cordova-sms/cordova-sms-plugin