Wednesday, January 30, 2013

HTML5 video tag in my Phone gap Android application


Here I am successfully running HTML5 <video> tag in my Phone gap Android application…
First thing here I succeeded in Android 3.2 version

There are two ways for running video by using <video> tag




1)      By using StrobeMediaPlayer

2)      Without any Player 

1)      Using StrobeMediaPlayer

For that I followed these steps.

1)      Download the StrobeMediaPlayer from the internet
2)      Findout the lib folder in ur downloaded zip file, that lib folder contains two folders (jquery , jscolor) and required js and css files
3)      Then add the lib folder in ur www folder



Required js files:
1)Profiles.js(Required)
2)devicedetection.js(Required)

3)jquery-1.5.1.min.js(Required)

4)jquery-ui-1.8.14.custom.min.js(optional) it displays video time

5)jquery.strobemediaplaybackhtml5.js(Required)

6)StrobeMediaPlayer.js(Required)

index.html

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Device Detection Test</title>
<style type="text/css">
body {
 font-family: sans-serif;
}

.movie {
 width: 100%;
 clear: both;
}

.movie div.thumb {
 float: left;
 margin-right: 10px;
 cursor: pointer;
 border: solid 1px blue;
}

.movie div.details {
 width: 100%;
 height: 100%;
}

.movie div.details p.title {
 font-weight: bold;
 cursor: pointer;
}

.movie div.details p.desc {
 font-weight: normal;
}
</style>
<link type="text/css" rel="stylesheet"
 href="lib/jquery.strobemediaplaybackhtml5.css" />

<script type="text/javascript" src="lib/profiles.js"></script>
<script type="text/javascript" src="lib/devicedetection.js"></script>
<script type="text/javascript" src="lib/jquery/jquery-1.5.1.min.js"></script>
<script type="text/javascript" src="lib/jquery-ui-1.8.14.custom.min.js"></script>
<script type="text/javascript"
 src="lib/jquery.strobemediaplaybackhtml5.js"></script>
<script type="text/javascript" src="lib/StrobeMediaPlayer.js"></script>
<script>
 var movies = [
   {
    "flashvars" : {
     "poster" : "http://www.osmf.org/dev/1.6gm/images/poster1.png",
     "src" : "http://players.edgesuite.net/videos/big_buck_bunny/bbb_448x252.mp4"
    },
    "element" : "clipContainer0"
   }, ];
 $(function() {
  for (i = 0; i < movies.length; i++) {
   strobeMediaPlayback.flashvars(movies[i]["flashvars"]);
   strobeMediaPlayback.draw(movies[i]["element"]);
  }
 });
</script>
</head>
<body>
 <div>Strobe Media Playback</div>
 <div id="movie0" class="movie">
  <div class="thumb">
   <div id="clipContainer0"></div>
  </div>
  <div class="details">
   <p class="title">Video One</p>
   <p class="desc">Video one description.</p>
  </div>
 </div>

</body>
</html>



----------------------END OF index.html --------------------

Then add these two classes in your source folder

1)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package com.phonegap.plugins.aVideo;

import org.json.JSONArray;
import org.json.JSONException;
import vPlayer.VideoPlayer;
import android.content.Intent;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

public class AVideo extends Plugin {

    /**
     * Executes the request and returns PluginResult.
     *
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
     */
    public PluginResult execute(String action, JSONArray args, String callbackId) {
        PluginResult.Status status = PluginResult.Status.OK;
        String result = "";

        try {
            if (action.equals("showVideo")) {
                result = this.showVideo(args.getString(0));
                if (result.length() > 0) {
                    status = PluginResult.Status.ERROR;
                }
            }
            return new PluginResult(status, result);
        } catch (JSONException e) {
            return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
        }
    }

    /**
     * Identifies if action to be executed returns a value and should be run synchronously.
     *
     * @param action    The action to execute
     * @return          T=returns value
     */
    public boolean isSynch(String action) {
        return false;
    }

    /**
     * Called by AccelBroker when listener is to be shut down.
     * Stop listener.
     */
    public void onDestroy() {
    }

    //--------------------------------------------------------------------------
    // LOCAL METHODS
    //--------------------------------------------------------------------------

    /**
     * Display a video with the specified name.
     *
     * @param videoName     The video to load.
     * @return              "" if ok, or error message.
     */
    public String showVideo(String videoName) {
     Log.d("logicmax", videoName);
     try {
            Intent intent = null;
                intent = new Intent().setClass(this.ctx, VideoPlayer.class);
               
                intent.putExtra("Nme", videoName);
                
            this.ctx.startActivity(intent);
            return "";
        } catch (android.content.ActivityNotFoundException e) {
            Log.d("logicmax","error");
         return e.toString();
            
        }
    }

}


--------------------------END OF AVIDEO.JAVA-----------------------

2)

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package vPlayer;

import nl.webkrackt.test.R;
import android.app.Activity;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.MediaController;
import android.widget.VideoView;


public class VideoPlayer extends Activity implements   MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {
  private VideoView mVideoView;
  private String Chemin;
  private int videoPosition;
  
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
   
  requestWindowFeature(Window.FEATURE_NO_TITLE);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
  getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  
  setContentView(R.layout.lv);
  mVideoView = (VideoView)findViewById(R.id.videoView);
     mVideoView.setOnErrorListener(this);
     mVideoView.setOnCompletionListener(this);

        Bundle returnData = (Bundle) getLastNonConfigurationInstance();
     if (returnData == null) {
      Bundle Params = getIntent().getExtras ();
      String pth = Params.getString("Nme");
      if(pth!=null)
       Chemin = "android.resource://"+getPackageName() +"/raw/" + pth;
      else
       finish();
       
       MediaController mediaController = new MediaController(this);
       mediaController.setAnchorView(mVideoView);
       mVideoView.setVideoURI(Uri.parse(Chemin));
       mVideoView.setMediaController(mediaController);
       mVideoView.requestFocus();
       //mVideoView.start();
     
     }
     else
     {
             Chemin = returnData.getString("LOCATION");
             videoPosition = returnData.getInt("POSITION");
             MediaController mediaController = new MediaController(this);
             mediaController.setAnchorView(mVideoView);          
       mVideoView.setMediaController(mediaController);
             mVideoView.setVideoURI(Uri.parse(Chemin));
             mVideoView.seekTo(videoPosition);
             
     }
 }
 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event) {
     if (keyCode == KeyEvent.KEYCODE_BACK ) {
         finish();
         return true;
     }
     return super.onKeyDown(keyCode, event);
 }


 @Override
 protected void onPause() {
  super.onPause();

  if (mVideoView!=null) {
    synchronized (mVideoView) {
     mVideoView.pause();     
   }
   
  }
  
 }
  @Override
  protected void onResume() {
   super.onResume();

   if (mVideoView!=null) {
     synchronized (mVideoView) {
      mVideoView.start();  
      setVisible(true);      
    }
    
   }

  
 }
  @Override
     public Object onRetainNonConfigurationInstance() {         
         videoPosition = mVideoView.getCurrentPosition();
         Bundle data = new Bundle();
         data.putString("LOCATION", Chemin);
         data.putInt("POSITION", videoPosition);
         return data;
     }
  
  @Override
  protected void onSaveInstanceState(Bundle outState) {
   super.onSaveInstanceState(outState);
    videoPosition = mVideoView.getCurrentPosition();
          Bundle data = new Bundle();
          data.putString("LOCATION", Chemin);
          data.putInt("POSITION", videoPosition);
  }
  
     public boolean onError(MediaPlayer player, int arg1, int arg2) {         
         finish();
         return false;
     }
  public void onCompletion(MediaPlayer mp) {
      finish();
  }
}


-------------------*END OF VIDEOPLAYER.JAVA*--------------------

Then add these two line in your Activity class after the super.loadUrl();

WebSettings settings = appView.getSettings();
settings.setPluginState(PluginState.ON);

4)Copy the below code and paste in StrobeMediaPlayer.js

var strobeMediaPlayback = function () {
 alert("StrobeMediaPlayBack first");
 var settings = {
  "tablet": {
   "startSize": {"width":480, "height":268},
   "wmode": "direct"
  },
  "smartphone": {
   "startSize": {"width":120, "height":67},
   "wmode": "direct"
  },
  "default": {
   "startSize": {"width":480, "height":268},
   "wmode": "direct"
  }
 };
 
 var flashvars = {};
 
 function getSettingByDeviceType(setting, deviceType, defaultValue) {
  if (deviceType in settings) {
   return (settings[deviceType][setting] ? settings[deviceType][setting] : defaultValue);
  }
  else {
   return (settings["default"][setting] ? settings["default"][setting] : defaultValue);
  }
 }
 
 return { 
  settings: function(object) {
   settings = $.extend(true, settings, object);
  },
  flashvars: function(object) {
   flashvars = $.extend(true, flashvars, object);
  },
  draw: function(element) {
   if (element && flashvars && flashvars["src"]) {
    var agent = window.location.hash.replace(/^#/, "");

    function onDeviceDetection(device) {
     var startSize = getSettingByDeviceType("startSize", device.getProfile().type, "");
  var html5divs = '<div class="html5player">' + '<div class="errorwindow"></div>' +'<div class="controls">' +'<div class="icon playtoggle">Play/Pause</div>' +'<div class="timestamp current">0:00</div>' +'<div class="progress">' +'<a class="slider"></a>' +'<div class="tracks">' +'<div class="seeking"></div>' +  '<div class="played"></div>' +'<div class="buffered"></div>' + '</div>' +'</div>' +'<div class="timestamp duration">0:00</div>' +'<div class="icon fullview">Full View</div>' +'</div>' +'<video width="500" height="400" preload="none" poster="' + flashvars["poster"] + '">' +'<source src="http://players.edgesuite.net/videos/big_buck_bunny/bbb_448x252.mp4" />' +'</video>'+ '</div>';

$("#" + element).html(html5divs);
$("#" + element + " .html5player").strobemediaplaybackhtml5();
  }
new DeviceDetection(agent).addCallback(onDeviceDetection).addProfiles(profiles).detect();
   }
  }
 }
}();


---------------------END OF StrobeMediaPlayer.js---------------------------

5)AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="nl.webkrackt.test"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <supports-screens
                android:largeScreens="true"
                android:normalScreens="true"
                android:smallScreens="true"
                android:resizeable="true"
                android:anyDensity="true"
                />
        <uses-permission android:name="android.permission.CAMERA" />
        <uses-permission android:name="android.permission.VIBRATE" />
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
        <uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
        <uses-permission android:name="android.permission.READ_PHONE_STATE" />
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.RECEIVE_SMS" />
        <uses-permission android:name="android.permission.RECORD_AUDIO" />
        <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
        <uses-permission android:name="android.permission.READ_CONTACTS" />
        <uses-permission android:name="android.permission.WRITE_CONTACTS" />   
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />  
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-sdk android:minSdkVersion="7" />

    <application android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:hardwareAccelerated="true" >
        <activity
            android:name=".VideoTestActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name="com.phonegap.DroidGap" android:label="@string/app_name"
   android:configChanges="orientation|keyboardHidden" >
   <intent-filter>
   </intent-filter>
  </activity>
  <activity android:name="vPlayer.VideoPlayer" android:label="@string/app_name"></activity>
    </application>

</manifest>


-------------------END OF ANDROIDMANIFEST.XML-------------------------


Observe above xml file addded android:hardwareAccelerated="true"  attribute in ur < application> tag



1) Without any Player


Here I don’t want to use any player for running html5 video tag for that I do the following steps

1)change the androidManifest.xml file

a)      In androidManifest.xml file i added the android:hardwareAccelerated=”true” for <application> tag
b)      Added code for doing PluginState True in Java file
The following code is added in java file after the super.loadUrl();

WebSettings settings = appView.getSettings();
settings.setPluginState(PluginState.ON);

4 comments:

  1. can you send total application in zip file to fermin@codemoved.com

    ReplyDelete
  2. please send me full Android Application Zip on

    kundan.kumar@dioxe.com

    kundan.raj1434@gmail.com


    ReplyDelete
  3. please send me full Android Application Zip on hossein.hariri@gmail.com

    ReplyDelete
  4. Thanks for the post, I am techno savvy. I believe you hit the nail right on the head. I am highly impressed with your blog. It is very nicely explained. Your article adds best knowledge to our Java Online Training from India. or learn thru Java Online Training from India Students.

    ReplyDelete