android简易网页播放器

android提供了MediaController播放器(使用mediaplay也是可以的)和网页加载控件webview,如何通过网页浏览方式调用MediaController播放需要解决如下几个问题:

 

1. 如何使用MediaController播放器。

2. 如何使用webview加载网页。

3. 网页脚本javascript如何调用android应用程序以及javascript和android应用程序直接的参数传递。

4. android的menu设置使用。

5. Apache环境搭建(我用的是LAMP)用于网页访问。

 

源代码分为android的java代码和资源文件代码以及一个简单的网页源码:

 

WebviewActivity.java

package tcl.webv;

import android.view.MenuItem;

import android.view.Menu;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
//import android.webkit.Websettings;

public class WebviewActivity extends Activity {
 private WebView web;
 private Handler mHandler;
 
 SharedPreferences prefs = null;
 private static final String MAIN_URL = "
http://192.168.1.31/site/index.php";
 final private int menuRefr = Menu.FIRST;
  final private int menuPrope=Menu.FIRST + 1;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  mHandler = new Handler();
  String defValue = null;
  String url;
  
  /*获取属性设置项*/
  prefs = PreferenceManager.getDefaultSharedPreferences(this);
  prefs.edit();
  
  /*从属性设置里面获取主页url*/
  url = prefs.getString("lctvmaipage", defValue);
  web = (WebView) findViewById(R.id.webView);
  
  /*设置网页默认颜色*/
  web.setBackgroundColor(Color.BLACK);
  
  /*网页内核设置*/
  web.setWebChromeClient(new WebChromeClient ());
  //web.setWebViewClient(new HelloWebViewClient ());
  
  /*网页脚本时使能*/
  web.getSettings().setJavaScriptEnabled(true);
  web.getSettings().setBuiltInZoomControls(true);
  web.loadUrl(url);
   
  /*用于android与网页javascript交互!*/
  web.addJavascriptInterface(new Object() {
   public void start( String mUrl,int x, int y, int w, int h) {
    final String pUrl = mUrl;
    final int p_x = x;
    final int p_y = y;
    final int p_w = w;
    final int p_h = h;
    
       mHandler.post(new Runnable() {
         public void run() {
         Intent intent_m = new Intent(WebviewActivity.this, tclVideoView.class);
        
         /*播放器的 坐标和宽高*/
       intent_m.putExtra("media_url", pUrl);
       intent_m.putExtra("pos_x", p_x);
       intent_m.putExtra("pos_y", p_y);
       intent_m.putExtra("pos_w", p_w);
       intent_m.putExtra("pos_h", p_h);
      
       startActivity(intent_m);
         }
       });
   }
   
   /*用于在javascript中加载网页*/
   public void load_url( String mUrl) {
    Log.i("test", "mUrl = "+mUrl);
    web.loadUrl(mUrl);
   }
   /*用于在javascript中退出网页*/
   public void exit() {
    finish();
   }
     }, "mediaPlay");
   web.loadUrl(url);
 }
 
 protected void onResume ()
   {
  String url;
  
  /*调用javascript接口通知网页播放完毕*/
  url = "javascript:onTrailerStop()";  
  web.loadUrl(url);
  super.onResume();
   }

 private class HelloWebViewClient extends WebViewClient {
  @Override
  public boolean shouldOverrideUrlLoading(WebView view, String url) {
   view.loadUrl(url);
   return true;
  }
 }
 
 /*菜单项添加*/
 public boolean onCreateOptionsMenu(Menu menu) {
  
  /*网页刷新项*/
  menu.add(0, menuRefr, Menu.NONE, "refresh");
  
  /*属性设置项*/
  menu.add(0, menuPrope, Menu.NONE, "property");
  return super.onCreateOptionsMenu(menu);
 }
 
 /*菜单选择*/
 public boolean onOptionsItemSelected(MenuItem item) {
  String defValue = null;
  switch (item.getItemId()) {
  
  /*网页刷新*/
  case menuRefr:
   web.loadUrl(prefs.getString("lctvmaipage", defValue));
   break;
   
  /*调出属性设置菜单*/ 
  case menuPrope:
   Intent prope = new Intent(WebviewActivity.this, LeastTVPropety.class);
   startActivity(prope);
   break;
  }
  return super.onOptionsItemSelected(item);
 }
 
 /*按键截取*/
 public boolean dispatchKeyEvent(KeyEvent event) {
  // TODO Auto-generated method stub
  boolean defValue = false;
  String url;
  
  /*截取遥控器按键,目的是不让浏览器处理按键,采用直接在 js中处理按键的方式*/
  if(event.getAction()== KeyEvent.ACTION_DOWN)
  {
   /*调用js的按键处理函数*/
   url = "javascript:onTCLKeyDown('" + event.getKeyCode() + "')";  
   web.loadUrl(url);
   Log.i("test", "event.getKeyCode() = "+event.getKeyCode() );
  }
  
  /*返回键让浏览器处理*/
  if(prefs.getBoolean("keyEnable", defValue)
     || event.KEYCODE_MENU == event.getKeyCode())
  {
   return super.dispatchKeyEvent(event);
  }
  else
  {
   return true;
  }
  

 }
}

tclVideoView.java

package tcl.webv;
/*
 * Copyright (C) 2009 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     
http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import android.app.Activity;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.Toast;
import android.widget.VideoView;

public class tclVideoView extends Activity {

    /**
     * TODO: Set the path variable to a streaming video URL or a local media
     * file path.
     */
    private String path = "/mnt/sdcard/ly.mp4";
    private VideoView mVideoView;
    private int width = 640;
    private int height = 320;
   
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.media);
        mVideoView = (VideoView) findViewById(R.id.surface_view);
        LinearLayout mly = (LinearLayout) findViewById(R.id.mlayout);
       
        /*获取播放url*/
        Bundle bundle = this.getIntent().getExtras();
  if(null != bundle)
  {
   path = bundle.getString("media_url");
  }
  
  /*url为空则弹出提示*/
        if (path == "") {
            // Tell the user to provide a media file URL/path.
            Toast.makeText(
      tclVideoView.this,
            "Please edit VideoViewDemo Activity, and set path"
                    + " variable to your media file URL/path",
            Toast.LENGTH_LONG).show();

        }
        else
        {
         /*设置播放器的坐标和宽高*/
         int pos_x = bundle.getInt("pos_x");
         int pos_y = bundle.getInt("pos_y");
         int pos_w = bundle.getInt("pos_w");
         int pos_h = bundle.getInt("pos_h");
         
         LayoutParams params = mVideoView.getLayoutParams();
         params.height = pos_h;
            params.width  = pos_w;
            mly.setPadding(pos_x,pos_y,0,0);
           
            /*
             * Alternatively,for streaming media you can use
             * mVideoView.setVideoURI(Uri.parse(URLstring));
            */
         mVideoView.setVideoURI(Uri.parse(path));
            mVideoView.setMediaController(new MediaController(this));
            mVideoView.requestFocus();
            mVideoView.start();
        }
        mVideoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
         
            /*when play finish then exit the play activity*/
            public void onCompletion(MediaPlayer mp) {
             mp.stop();
             finish();
            }
        });
        mVideoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
    
   @Override
   public boolean onError(MediaPlayer mp, int what, int extra) {
    
    /*如果播放失败则播放默认的
http://192.168.1.31/site/wild.mp4*/
    mVideoView.setVideoURI(Uri.parse("http://192.168.1.31/site/wild.mp4"));
             mVideoView.start();
            
             /*返回true播放失败后播放器不弹出提示,如果返回false播放器出错后会弹出提示*/
    return true;
   }
  });
    } 
    public void onStop ()
   { 
       /*停止播放*/
       mVideoView.stopPlayback();
       super.onStop();
       return ;
   } 
    public boolean dispatchKeyEvent(KeyEvent event) {
  // TODO Auto-generated method stub
  
  /*播放的时候按任何一个按键推出播放返回网页*/
  if(event.getAction()== KeyEvent.ACTION_DOWN)
  {
   mVideoView.stopPlayback();
   finish();
  } 
  return super.dispatchKeyEvent(event);
 }
}

 

LeastTVPropety.java

 

package tcl.webv;

import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.PreferenceActivity;

public class LeastTVPropety extends PreferenceActivity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  
  /*属性设置布局*/
        addPreferencesFromResource(R.layout.pref_page);
 }
 
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none"
    >
    <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent"></WebView>
</LinearLayout>

 media.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="
http://schemas.android.com/apk/res/android"
android:id="@+id/mlayout"
    android:orientation="vertical"
    android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:background="#bb000000"
    android:paddingTop="0dip"
    android:paddingLeft="100dip">
    >
<VideoView
 android:id="@+id/surface_view"
 android:layout_width="640dip"
    android:layout_height="320dip"
>
 </VideoView>
</LinearLayout>

 

pref_page.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="
http://schemas.android.com/apk/res/android">
   <ListPreference
                android:summary="Select a user"
                android:title="Player Name"
                android:key="playerName" android:singleLine="true" android:name="playerName"
                android:entries="@array/player_names"
                android:entryValues="@array/player_names"/>
  <ListPreference
                android:summary="Select a queue"
                android:title="Message Queue"
                android:key="queueUrl" android:singleLine="true" android:name="LCTQueueUrl"
                android:entries="@array/main_page"
                android:entryValues="@array/queue_urls"/>
   <CheckBoxPreference           
       android:key="keyEnable"           
       android:title="Key Enable" />                      
 <EditTextPreference
                android:name="lctvMainPage"
                android:title="Main Page"
                android:singleLine="true"
                android:defaultValue = "
http://www.google.com"
                android:key="lctvmaipage" /> 
    <EditTextPreference
       android:id="@+id/did"
                android:name="deviceid"
                android:title="Device ID"
                android:singleLine="true"
                android:defaultValue = "1"
                android:key="did" /> 
</PreferenceScreen>

 

strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">Hello World, WebviewActivity!</string>
    <string name="app_name">LeastClickTV</string>
   
    <string-array name="player_names">
    <item>Tcl Xman player</item>
     <item>media player</item>
     <item>storm pkayer</item>
    </string-array>
 
     <string-array name="main_page">
    <item>tcl cloud</item>
     <item>sina</item>
     <item>sohu</item>
    </string-array>
    <string-array name="queue_urls">
    <item>https://192.168.1.31/site/index.php</item>
     <item>http://www.sina.com.cn</item>
     <item>http://www.sohu.com.cn</item>
    </string-array>
</resources>

 androidMainfest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="
http://schemas.android.com/apk/res/android"
      package="tcl.webv"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
    <application android:icon="@drawable/jj" android:label="@string/app_name">
        <activity android:name=".WebviewActivity"
        android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
                  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=".tclVideoView"
  android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>
        <activity android:name=".LeastTVPropety"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
            </intent-filter>
        </activity>

    </application>
</manifest>

 

网页:

<html>    
        <script language="javascript">   
         var url = "/mnt/sdcard/ly.mp4";
          function playit() {  
              obj = document.getElementById('fname');
              url = obj.value;
     alert(url);
              window.mediaPlay.start(url,0,0,600,400);
          }    
          function onTCLKeyDown(t) {    
              obj = document.getElementById('testtest');
     obj.innerHTML = "code="+t;
      
          }    
        </script>    
        <body>    
          <br /><br />
            <b id="note">please enter a play URL</b> <br/> <br />
            <form action="form_action.asp" method="get" name="mainForm">
       URL: <input type="text" name="fname" id = "fname" value="
http://192.168.1.31/site/wild.mp4"/><br /><br />
       <input type="button" value="play" OnClick="playit()"/>
      </form>
      <div id=testtest><a href=# onClick="testit('hello')">TestTest</a></div>
        </body>    
</html> 

你可能感兴趣的:(JavaScript,android,String,layout,url,encoding)