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

本文介绍一下开发和使用插件的一个流程,以 VideoPlayer 为例。
- 环境搭建,下载 phonegap-android 的源码,下载地址 https://github.com/phonegap/phonegap-plugins
- 编写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函数调用
<script type="text/javascript" charset="utf-8" src="phonegap.js"></script>
<script type="text/javascript" charset="utf-8" src="video.js"></script>
//Sample use:
/**
* Display an intent to play the video.
*
* @param url The url to play
*/
//play(url)
window.plugins.videoPlayer.play("http://path.to.my/video.mp4");
window.plugins.videoPlayer.play("file:///path/to/my/video.mp4");
- 到此为止,插件的开发和部署,以及调用就都ok了,是不是很简单( ⊙ o ⊙ )啊!
最后向大家推荐一本书籍《PhoneGap Beginner’s Guide》,相信通过本书的学习,就知道了怎样利用PhoneGap来开发跨平台的mobile app了,同时也可以关注 https://github.com/phonegap 项目的最新进展情况和新特性,如果可以的话,贡献自己的力量来进行完善和扩充,O(∩_∩)O~!
历史评论 · 1 条
只读存档以下评论来自原 WordPress 站点,已剔除邮箱、IP、浏览器标识与用户 ID,正文中的个人信息也已掩码。这是内容保全存档,不参与新评论的回复;想说点什么,请到下方「加入讨论」。