Andriod Phonegap(Cordova自定義插件)

1.首先介紹phonegap必備的兩個文件,分別是本地.java代碼Share.java

/**
 * 
 * Phonegap share plugin for Android
 * Kevin Schaul 2011
 *
 */

package com.tricedesigns;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;

public class Share extends Plugin {

 @Override
 public PluginResult execute(String action, JSONArray args, String callbackId) {
  try {
   JSONObject jo = args.getJSONObject(0);
   doSendIntent(jo.getString("subject"), jo.getString("text")); 
   return new PluginResult(PluginResult.Status.OK);
  } catch (JSONException e) {
   return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
  }
 }
 
 private void doSendIntent(String subject, String text) {
  Intent sendIntent = new Intent(android.content.Intent.ACTION_SEND);
  sendIntent.setType("text/plain");
  sendIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
  sendIntent.putExtra(android.content.Intent.EXTRA_TEXT, text);
  this.cordova.startActivityForResult(this, sendIntent, 0);
 }

}

2.(.js文件share.js)
/**
 * 
 * Phonegap share plugin for Android
 * Kevin Schaul 2011
 *
 */
 
var Share = {
        show:function(content, success, fail) {
            return cordova.exec( function(args) {
                success(args);
            }, function(args) {
                fail(args);
            }, 'Share', '', [content]);
        }
};

 

3.而後咱們在phonegap項目中添加上述兩個文件

 

4.在plugin.xml中添加語句(記得修改packageName)

<plugin name="Share" value="com.schaul.plugins.share.Share"/>

5.定義調用的js
function shareClick(){
        Share.show({
            subject: 'I like turtles',
            text: 'http://www.mndaily.com'},
            function() {}, // Success function
            function() {alert('Share failed')} // Failure function
        );
    }