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函數調用
- <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了,是不是很簡單啊!
最后向大家推薦一本書籍《PhoneGap Beginner’s Guide》,相信通過本書的學習,就知道了怎樣利用PhoneGap來開發跨平臺的mobile app了,同時也可以關注https://github.com/phonegap項目的最新進展情況和新特性,如果可以的話,貢獻自己的力量來進行完善和擴充!