PhoneGap的Android端插件开发
前面一篇文章 《移动 APP 之跨平台解决方案》 介绍了一种跨平台的解决方案,即用开发web app的方式来编写mobile app。鉴于PhoneGap才刚刚新起,还有许多功能因为平台的差异性无法很好的解决,所以我们在实际的开发中,发现有很多功能还需要完善,一种比较好 的方式就是编写平台依赖的插件,进而扩展PhoneGap的功能。

本文介绍一下开发和使用插件的一个流程,以 VideoPlayer 为例。
- 环境搭建,下载 phonegap-android 的源码,下载地址 https://github.com/phonegap/phonegap-android
- 编写video.js,提供给web开发端的接口定义,定义了一个VideoPlayer类和play函数,参数为要播放的文件视频地址,代码如下:
/**
* Constructor
*/
function VideoPlayer() {
};
/**
* Starts the video player intent
*
* @param url The url to play
*/
VideoPlayer.prototype.play = function(url) {
PhoneGap.exec(null, null, "VideoPlayer", "playVideo", [url]);
};
/**
* Load VideoPlayer
*/
PhoneGap.addConstructor(function() {
PhoneGap.addPlugin("videoPlayer", new VideoPlayer());
}); 编写 Android VideoPlayer 的具体实现代码,VideoPlayer/src/com/phonegap/plugins/video/VideoPlayer.java package com.phonegap.plugins.video;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.Intent;
import android.net.Uri;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
public class VideoPlayer extends Plugin {
private static final String YOU_TUBE = "youtube.com";
@Override
public PluginResult execute(String action, JSONArray args, String callbackId) {
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("playVideo")) {
playVideo(args.getString(0));
}
else {
status = PluginResult.Status.INVALID_ACTION;
}
return new PluginResult(status, result);
} catch (JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void playVideo(String url) {
// Create URI
Uri uri = Uri.parse(url);
Intent intent = null;
// Check to see if someone is trying to play a YouTube page.
if (url.contains(YOU_TUBE)) {
// If we don't do it this way you don't have the option for youtube
intent = new Intent(Intent.ACTION_VIEW, uri);
} else {
// Display video player
intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "video/*");
}
this.ctx.startActivity(intent);
}
} 配置插件, res/xml/plugins.xml 添加如下代码 <plugin name="VideoPlayer" value="com.phonegap.plugins.video.VideoPlayer"/>编写代码进行调用,文件开头引入js代码框架,然后进行VideoPlayer类的play函数调用
相关推荐
quzishen 2013-07-17
故作坚强 2013-07-15
爱技术爱生活TAO 2013-07-06
临碣秘藏 2013-07-10
czpaex 2011-09-11
益之 2014-01-09
yxwang0 2014-01-09
朱莉的乔夫 2014-09-05
朱莉的乔夫 2015-03-26
朱莉的乔夫 2015-03-13
益之 2015-04-21
临碣秘藏 2015-05-12
quzishen 2016-01-20
爱技术爱生活TAO 2016-01-07
tenda 2012-09-08
临碣秘藏 2012-05-30
老菜鸟自习室 2012-04-07