PhoneGap2.90 (Android)视频插件调用

用HTML打包了一个PhoneGap(Android)的APP发如今Android2.3上不能播放视频,又测试了一下Android2.3自带浏览器,发现打开视频页面秒退,打开国内几个视频网站也是秒退。java

上网看了部分资料,PhoneGap是基webkit浏览器为载体的封装,要调用视频就要开发插件,还好有网友开发出了相关插件,试用了几个,成功了一下拿出来分享一下。android

原插件地址:https://github.com/mllrsohn/phonegap-videodialoggit

调用步骤1:github

如上图,新建类文件VideoDialogPlugin.java,拷贝下面代码到类文件,注意要修改代码中 package com.example.mb ,简单的做法就是和MainActivity.java 中package 同样。web

/*
 * VideoDialogPlugin
 * MIT License. See http://opensource.org/licenses/alphabetical for full text.
 *
 * Based on the amazing work by macdonst: https://github.com/macdonst/VideoPlayer
 * Copyright (c) 2013, Steffen M眉ller, M眉ller & Sohn Digitalmanufaktur GmbH
 *
 */

package com.example.mb;

import android.media.MediaPlayer;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.RelativeLayout;
import android.widget.VideoView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import org.apache.cordova.api.CallbackContext;
import org.apache.cordova.api.CordovaPlugin;
import org.apache.cordova.api.PluginResult;

import java.io.*;
import android.net.Uri;
import android.view.WindowManager.LayoutParams;

import java.io.IOException;

public class VideoDialogPlugin extends CordovaPlugin {
    private static final String ASSETS = "file:///android_asset/";
    private Dialog dialog;
    private VideoView mVideoView;
    private boolean loopVideo = false;
    private String path = "";
    private Uri uri;
    public CallbackContext cbContext;

    @Override
    public boolean execute(String action, JSONArray args, final CallbackContext callbackContext) throws JSONException {
        JSONObject params;

        try {
            if (action.equals("play")) {
                // If the VideoDiaolog is already open then throw an error
                if (dialog != null && dialog.isShowing()) {
                    callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "VideoDialog is already open"));
                    return false;
                } else {
                    params = args.getJSONObject(0);
                    playVideo(params, callbackContext);
                    return true;
                }

            } else {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.INVALID_ACTION, "VideoDialog Action is not implemented"));
                return false;
            }
        } catch (JSONException e) {
            callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.MALFORMED_URL_EXCEPTION, "UTF-8 error."));
        }
        return false;
    }

    private void playVideo(JSONObject params, final CallbackContext callbackContext) throws JSONException {

        loopVideo = params.optBoolean("loop", true);
        path = params.optString("url");

        uri = Uri.parse(path);

        if(path.contains(ASSETS)) {
            try {
                String filepath = path.replace(ASSETS, "");
                String filename = filepath.substring(filepath.lastIndexOf("/")+1, filepath.length());
                File fp = new File(this.cordova.getActivity().getFilesDir() + "/" + filename);

                if (!fp.exists()) {
                    this.copy(filepath, filename);
                }
                uri = Uri.parse("file://" + this.cordova.getActivity().getFilesDir() + "/" + filename);
            } catch (IOException e) {
                callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.IO_EXCEPTION));
            }

        }

        // Create dialog in new thread
        cordova.getActivity().runOnUiThread(new Runnable() {
            public void run() {

                // Set Basic Dialog
                dialog = new Dialog((Context) cordova.getActivity(), android.R.style.Theme_NoTitleBar_Fullscreen);
                dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
                dialog.setCancelable(true);

                // Layout View
                RelativeLayout main = new RelativeLayout((Context) cordova.getActivity());
                main.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));


                // Video View
                mVideoView = new VideoView((Context) cordova.getActivity());
                RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
                lp.addRule(RelativeLayout.CENTER_IN_PARENT);
                mVideoView.setLayoutParams(lp);

                mVideoView.setVideoPath(uri.toString());
                mVideoView.start();
                main.addView(mVideoView);

                dialog.setContentView(main);
                dialog.getWindow().setFlags(LayoutParams.FLAG_FULLSCREEN, LayoutParams.FLAG_FULLSCREEN);
                dialog.show();

                // Close on touch
                mVideoView.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.ERROR, "stopped"));
                        dialog.dismiss();
                        return true;
                    }
                });

                // Set Looping
                mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.setLooping(loopVideo);
                    }
                });

                // On Completion
                mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(MediaPlayer mediaplayer) {
                        callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, "Done"));
                        dialog.dismiss();
                    }
                });

            }
        });
    }

    /**
     * Closes the dialog
     */
    private void closeDialog() {
        if (dialog != null) {
            //this.webview.stopLoading();
            dialog.dismiss();
        }
    }

    private void copy(String fileFrom, String fileTo) throws IOException {
        // get file to be copied from assets
        InputStream in = this.cordova.getActivity().getAssets().open(fileFrom);
        // get file where copied too, in internal storage.
        // must be MODE_WORLD_READABLE or Android can't play it
        FileOutputStream out = this.cordova.getActivity().openFileOutput(fileTo, Context.MODE_WORLD_READABLE);

        // Transfer bytes from in to out
        byte[] buf = new byte[1024];
        int len;
        while ((len = in.read(buf)) > 0)
            out.write(buf, 0, len);
        in.close();
        out.close();
    }
}

调用步骤2:apache

在项目assets\www路径下新建videodialog.js文件,JS内容以下:json

cordova.define("cordova/plugin/videodialog",
  function(require, exports, module) {
    var exec = require("cordova/exec");
    var VideoDialog = function () {};

    VideoDialog.prototype.play = function(url, options, successCallback, errorCallback) {
        if (!options) {
            options = {};
        }
        var params = {
            url: url,
            loop : (options.loop === true ? true : false)
        };

        if (typeof errorCallback !== "function")  {
            errorCallback = function() {};
        }

        if (typeof successCallback !== "function")  {
            errorCallback = function() {};
        }

        if (url === undefined)  {
            console.log("VideoView.play failure! Please specify a url");
            return false;
        }

        exec(successCallback, errorCallback, "VideoDialogPlugin", "play", [params]);
    };

    var videodialog = new VideoDialog();
    module.exports = videodialog;
});

if (!window.plugins) {
    window.plugins = {};
}
if (!window.plugins.VideoView) {
    window.plugins.VideoDialog = cordova.require("cordova/plugin/videodialog");
}

调用步骤3:api

打开项目路径 res\xml\config.xml 文件,在<plugins></plugins>标签之间添加<plugin name="VideoDialogPlugin" value="com.example.mb.VideoDialogPlugin"/>浏览器

注意:value值中com.example.mb修改为自个项目中VideoDialogPlugin.java代码中的 package网络

调用步骤4:

在调用的页面用JS就能够调用,注意的是 【file:///表明本地调用】【 http://表明网络调用】 ,代码以下:

window.plugins.VideoDialog.play("http://www.****.com/Video.mp4");//调用方式1
window.plugins.VideoDialog.play("file:///android_asset/www/Video.mp4");//调用方式2
window.plugins.VideoDialog.play("file:///android_asset/www/Video.mp4", {loop : true});//调用方式3
window.plugins.VideoDialog.play("file:///android_asset/www/Video.mp4", {loop : true},
    function() {
        console.log('Video played until the end');
    }, function() {
        console.log('User interupted video');
    }
);//调用方式4

模拟器一个字慢,仍是真机测试快。

测试成功,收工。

相关文章
相关标签/搜索