转自:http://blog.csdn.net/avenleft/article/details/7383294
目前PhoneGap虽然提供了很多的API,但是我们也很容易发现,他有很多地方不能满足我们的需求,比如发短信。我也将介绍如何开发一个针对PhoneGap发短信的Plugin。(Android 版本)。
1、创建一个Android工程,创建之后的目录结构如图:
2、把PhoneGap的android版jar包、javascript和xml文件夹加入工程。(参照上一篇中的做法)目录结构:
3、新增一个类MessagePlugin
这个类就是负责发送短信功能的具体类,可以调用发送短信的android API,当然如果是其他功能,则调用相应的API,但是当使用这个API时记得申请权限。
具体代码:
- package com.phonegap.kiddyu.plugin;
- import org.json.JSONArray;
- import org.json.JSONException;
- import org.json.JSONObject;
- import android.telephony.SmsManager;
- import com.phonegap.api.Plugin;
- import com.phonegap.api.PluginResult;
-
public class MessagePlugin extends Plugin
{ -
private static final String
SEND = "send"; - @Override
-
public PluginResult
execute(String action, JSONArray data, String callbackId) { - PluginResult result;
-
if (SEND.equals(action))
{ - try {
- JSONObject jsonObj = new JSONObject();
- String target = data.getString(0);
- String content = data.getString(1);
- SmsManager sms = SmsManager.getDefault();
-
sms.sendTextMessage(target, null,
content, null, null); -
jsonObj.put("target",
target); -
jsonObj.put("content",
content); -
result = new PluginResult(PluginResult.Status.OK,
jsonObj); -
} catch (JSONException
ex) { - result = new PluginResult(PluginResult.Status.JSON_EXCEPTION);
-
}catch(IllegalArgumentException
ex){ - result = new PluginResult(PluginResult.Status.ERROR);
- }
- } else {
- result = new PluginResult(PluginResult.Status.INVALID_ACTION);
- }
- return result;
- }
- }
4、为phonegap增加一个javascript的API
在工程目录www/js下面增加一个javascript文件:phonegapPlugin.js,然后加入代码:
-
var Message
= function(){}; - Message.prototype = {
-
send: function(success,
error, target, content){ -
PhoneGap.exec(success, error, "MessagePlugin", "send",
[target, content]); - }
- };
-
PhoneGap.addConstructor(function()
{ - PhoneGap.addPlugin("message", new Message());
- });
- var Message = function(){};
- Message.prototype = {
- send: function(success, error, target, content){
- PhoneGap.exec(success, error, "MessagePlugin", "send", [target, content]);
- }
- };
- PhoneGap.addConstructor(function() {
- PhoneGap.addPlugin("message", new Message());
- });
关键的方法是PhoneGap.exec(success, error, "MessagePlugin", "send", [target, content]);