import android.content.ContentResolver;import android.content.Context;import android.os.Build;import android.widget.ResourceCursorAdapter;public abstract class EmailAddressAdapter extends ResourceCursorAdapter{    private static EmailAddressAdapter sInstance;    private static Context sContext;    public static EmailAddressAdapter getInstance(Context context)    {        if (sInstance == null)        {            String className;            sContext = context;            /*             * Check the version of the SDK we are running on. Choose an             * implementation class designed for that version of the SDK.             */            @SuppressWarnings("deprecation")            int sdkVersion = Integer.parseInt(Build.VERSION.SDK);       // Cupcake style            if (sdkVersion < Build.VERSION_CODES.ECLAIR)            {                className = "com.archermind.uitl.EmailAddressAdapterSdk3_4";            }            else            {                className = "com.archermind.uitl.EmailAddressAdapterSdk5";            }            /*             * Find the required class by name and instantiate it.             */            try            {                Class<? extends EmailAddressAdapter> clazz =                    Class.forName(className).asSubclass(EmailAddressAdapter.class);                sInstance = clazz.newInstance();            }            catch (Exception e)            {                throw new IllegalStateException(e);            }        }        return sInstance;    }    public static Context getContext()    {        return sContext;    }    protected ContentResolver mContentResolver;    public EmailAddressAdapter()    {        super(getContext(), R.layout.recipient_dropdown_item, null);        mContentResolver = getContext().getContentResolver();    }}


package com.wt.app;import java.util.ArrayList;import java.util.HashMap;import android.app.Activity;import android.os.Bundle;import android.view.ContextMenu;import android.view.MenuItem;import android.view.View;import android.view.ContextMenu.ContextMenuInfo;import android.view.View.OnCreateContextMenuListener;import android.widget.AdapterView;import android.widget.ListView;import android.widget.SimpleAdapter;import android.widget.AdapterView.OnItemClickListener;public class App extends Activity {@Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        //绑定Layout里面的ListView        ListView list = (ListView) findViewById(R.id.ListView01);                //生成动态数组,加入数据        ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();        int[] images=new int[]{android.R.drawable.ic_menu_add,android.R.drawable.ic_menu_delete,android.R.drawable.ic_menu_edit,android.R.drawable.ic_menu_view};        for(int i=0;i<4;i++)        {        HashMap<String, Object> map = new HashMap<String, Object>();        map.put("itemImage", images[i]);//图像资源的ID        map.put("itemTitle", "Title "+i);        map.put("itemText", "this is Text "+i);        listItem.add(map);        }        //生成适配器的Item和动态数组对应的元素        SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//数据源             R.layout.row,//ListItem的XML实现            //动态数组与ImageItem对应的子项                    new String[] {"itemImage","itemTitle", "itemText"},             //ImageItem的XML文件里面的一个ImageView,两个TextView ID            new int[] {R.id.itemImage,R.id.itemTitle,R.id.itemText}        );               //添加并且显示        list.setAdapter(listItemAdapter);        //添加点击        list.setOnItemClickListener(new OnItemClickListener() {public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {setTitle("点击第"+arg2+"个项目");}});              //添加长按点击        list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {menu.setHeaderTitle("长按菜单-ContextMenu");   menu.add(0, 0, 0, "弹出长按菜单0");menu.add(0, 1, 0, "弹出长按菜单1");   }});     }//长按菜单响应函数@Overridepublic boolean onContextItemSelected(MenuItem item) {setTitle("点击了长按菜单里面的第"+item.getItemId()+"个项目"); return super.onContextItemSelected(item);}}

<?xml version="1.0" encoding="utf-8"?><RelativeLayout android:id="@+id/RelativeLayout01" android:layout_width="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_height="wrap_content" android:paddingTop="4dip" android:paddingBottom="4dip" android:paddingLeft="12dip"android:paddingRight="12dip"><ImageView android:paddingTop="12dip"android:layout_alignParentRight="true"android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/itemImage"/> <TextView     android:layout_height="wrap_content"     android:textSize="20dip"     android:layout_width="fill_parent"     android:id="@+id/itemTitle"    /><TextView android:layout_height="wrap_content" android:layout_width="fill_parent" android:layout_below="@+id/itemTitle" android:id="@+id/itemText"/></RelativeLayout>

<?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"    ><ListView android:layout_width="wrap_content"             android:layout_height="wrap_content"             android:id="@+id/ListView01"      />  </LinearLayout>

/** * 在第一个字符串中查找匹配字符串的个数 * @param str   * @param regexStr * @return */public static int count(String str,String regexStr){int count = 0;Pattern pt = Pattern.compile(regexStr);Matcher m = pt.matcher(str);int start = 0;while(m.find()){count++;}return count;}/** * 根据正则表达式分割str字符串成为一个一个的小的单元!         * (实际使用:在一个类似语法分析的模块中发挥重要作用) * 例如:3+5*4  根据正则表达式+-\*  分割成数组  3,+,5,*,4   * @param str * @param regexStr * @return */public static List splitByStr(String str,String regexStr){List temp = new ArrayList();Pattern pt = Pattern.compile(regexStr);Matcher m = pt.matcher(str);int start = 0;while(m.find()){//去掉下面的字符串中为空串的情况!if(m.start()!=start)temp.add(str.substring(start, m.start()));temp.add(str.substring(m.start(),m.end()));start = m.end();}temp.add(str.substring(start));return temp;}      /** * 检查是否含有指定的正则表达式匹配的子串. * @param str 目标字符串 * @param regex 正则表达式,如果正则表达式含有"^......$"就是查找整个字符串对象是否符合正则表达式. * @return */public static boolean checkInclude(String str,String regex){ Pattern pattern = Pattern.compile(regex);         Matcher matcher = null;         matcher = pattern.matcher(str);         return matcher.find();}/** * 方法字符串中符合正则表达式的子串的集合. * @param str * @param regex * @return */public static List getRightSubStr(String str, String regex) {List ans = new ArrayList();Pattern pattern = Pattern.compile(regex);Matcher matcher = pattern.matcher(str);while (matcher.find()) {//注意要下面的goup()函数中可以含有数字,表示查找得到正则表达式中的goup匹配串.ans.add(matcher.group());System.out.println("找到匹配的字符串 \"" + matcher.group()+ "\" 开始于 " + matcher.start()+ " 结束于 " + matcher.end() + ".");}return ans;}

(1)使用matches方法快速建设是否表示给定的输入字符串:Pattern.matches("\\d","1")返回true(2)split(string)使用方法:Pattern.compile(":").split("one:two:three:four:five");  返回:解析出“one two three four five”单词再比如使用数字作为一个分割字符串的方法:(注意下面的\\d不是正则表达式,而是前面加了一个转义符号\)Pattern.compile("\\d").split("one9two4three7four1five");也返回相同的结果。。(3)在String类中有的几个与Pattern类似的方法:public boolean matches(String regex):public String[] split(String regex, int limit):public String[] split(String regex):public String replace(CharSequence target,CharSequence replacement):(4) Matcher 类中其他一些有用的方法索引方法  索引方法(index methods)提供了一些正好在输入字符串中发现匹配的索引值:  public int start():返回之前匹配的开始索引。  public int start(int group):返回之前匹配操作中通过给定组所捕获序列的开始索引。  public int end(): 返回最后匹配字符后的偏移量。  public int end(int group): 返回之前匹配操作中通过给定组所捕获序列的最后字符之后的偏移量。 研究方法  研究方法(study methods)回顾输入的字符串,并且返回一个用于指示是否找到模式的布尔值。  public boolean lookingAt(): 尝试从区域开头处开始,输入序列与该模式匹配。  public boolean find(): 尝试地寻找输入序列中,匹配模式的下一个子序列。  public boolean find(int start): 重置匹配器,然后从指定的索引处开始,尝试地寻找输入序列中,匹配模式的下一个子序列。  public boolean matches(): 尝试将整个区域与模式进行匹配 替换方法  替换方法(replacement methods)用于在输入的字符串中替换文本有用处的方法。  public Matcher appendReplacement(StringBuffer sb, String replacement):实现非结尾处的增加和替换操作。  public StringBuffer appendTail(StringBuffer sb):实现结尾处的增加和替换操作。  public String replaceAll(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的每一个子序列。  public String replaceFirst(String replacement):使用给定的替换字符串来替换输入序列中匹配模式的第一个子序列。  public static String quoteReplacement(String s):返回指定字符串的字面值来替换字符串。这个方法会生成一个字符串,用作 Matcher 的 appendReplacement 方法中的字面值替换 s。所产生的字符串将与作为字面值序列的 s 中的字符序列匹配。斜线(\)和美元符号($)将不再有特殊意义了。 


10,29,3,4,5,0,0,12,0,2,4,1,12,7,11,1,0,8,1,3,11,11,2,0,5,6,2,7,8,4,14,3,17,9,1|4,0,5,28,2,9,2,8,8,5,4,0
import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.TreeMap;public class HashMapTest {public static void getMiss(String[] split){TreeMap<String,String> map=new TreeMap<String,String>();List<String> list=new ArrayList<String>();String key=null;//将数据添加入TreeMapfor(int i=1;i<=split.length;i++){if(i<10){key="0"+i;}else{key=""+i;}if(split[i-1].equals("0")){//如果为0,不加入maplist.add(key);}else{map.put(key, split[i-1]);}}//打印listfor(int i=0;i<list.size();i++){if(i!=list.size()-1){System.out.print(list.get(i)+",");}else{System.out.print(list.get(i)+":0");}}System.out.println();//打印mapIterator iterator =  map.entrySet().iterator();while (iterator.hasNext()) {Map.Entry mapentry = (Map.Entry)iterator.next();System.out.println(mapentry.getKey() + ":" + mapentry.getValue());}}public static void main(String[] args) {// TODO Auto-generated method stubString temp="10,29,3,4,5,0,0,12,0,2,4,1,12,7,11,1,0,8,1,3,11,11,2,0,5,6,2,7,8,4,14,3,17,9,1|4,0,5,28,2,9,2,8,8,5,4,0";//String s="10,29,3,4,5,0,0,12,0,2,4,1,12,7,11,1,0,8,1,3,11,11,2,0,5,6,2,7,8,4,14,3,17,9,1";String[] split_front=temp.split("\\|")[0].split(",");String[] split_behide=temp.split("\\|")[1].split(",");getMiss(split_front);getMiss(split_behide);}}


Dom4j+Xpath
http://newbutton.blog.163.com/blog/static/440539462007919115928634/

查手机UA
UA=<%=request.getHeader("User-Agent")%>
或试试下面这个:
var sUserAgent = window.navigator.userAgent;

jquery grid插件 Flexigrid
http://blog.csdn.net/yuanxiaogang/archive/2009/04/01/4041232.aspx

jspSmartUpload使用
http://hi.baidu.com/stream1990/blog/item/fccd60d7ae46cd2607088bef.html
使用jspSmartUpload组件应注意几点小问题
http://hi.baidu.com/%CD%F2%B4%BA%C0%F6/blog/item/e8a373519071de2c42a75b92.html
利用Jakarta commons fileupload组件实现多文件上传
http://blog.csdn.net/hbcui1984/archive/2007/05/25/1625754.aspx
对commons fileupload组件的简单封装
http://blog.csdn.net/hbcui1984/archive/2007/05/29/1629151.aspx

在Eclipse中编写JavaFX
http://blog.csdn.net/BU_BetterYou/archive/2008/06/26/2589528.aspx

HttpSessionListener和HttpSessionBindingListener
http://hi.baidu.com/lurim/blog/item/b6f3872da286c2e68a1399e2.html

基于hibernate的泛型Dao框架
http://llying.iteye.com/blog/406058

hibernate 操作 模板基类设计
http://www.iteye.com/topic/348531

Hibernate 数据库操作 模板基类 实现类GenericHibernateDao
http://www.iteye.com/topic/384199

应用Hibernate3的DetachedCriteria实现分页查询
http://www.iteye.com/topic/14657


利用java操作Excel文件
http://www.iteye.com/topic/55844

http://www.ibm.com/developerworks/cn/java/l-javaExcel/?ca=j-t10

http://sourceforge.net/project/showfiles.php?group_id=79926

http://fins.iteye.com/blog/313136

好用的复选树源码改进版
http://cxlh.iteye.com/blog/419010

getScheme()方法返回请求的计划,比如http,https或者ftp.
getServerName()方法返回被发送请求的服务器的主机名
getServerPort()方法返回被发送请求的端口号。
getContextPath()返回请求地址的根目录,以"/"开关,但不是以"/"结尾。

一个常用的获得服务器地址的连接字符串是:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

1:先来个简单的
“用户登录一次后,一个月内不需要再次登录,请给出实现方法,用cookie实现"
cookie setMaxAge

   1. if (Request.Cookies["UserName"] != null)     2. {     3. Response.Redirect("B.aspx?UserName=" + Request.Cookies["UserName"].Value);     4. }     5. else     6. {     7. if(this.txtName.Text=="A"&&this.txtPassword.Text=="a")     8. {     9. if (CheckBox1.Checked == true)    10. {    11. Response.Cookies["UserName"].Value = System.Web.HttpUtility.UrlEncode(txtName.Text);    12. Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(14);    13. }    14. Response.Redirect("B.aspx?UserName=" + System.Web.HttpUtility.UrlEncode(txtName.Text));    15.     16. }    17. else     18. {    19. Response.Write("<script>alert('输入出错!')</script>");    20. }    21. }  

2:请问如何禁止某一固定IP 访问论坛,列出您所知道的方法,可以编程实现也可以采用其他途径! request.getRemoteAddr


SELECT * FROM 表 WHERE id=2
UNION
SELECT A.* FROM(SELECT * FROM 表 WHERE id<2 ORDER BY id DESC LIMIT 0,1) AS A
UNION
SELECT B.* FROM(SELECT * FROM 表 WHERE id>2 LIMIT 0,1) AS B





truncate v.把(某物)截短,去尾import java.io.DataOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Calendar;import java.util.Enumeration;import java.util.Vector;import javax.microedition.io.Connector;import javax.microedition.io.file.FileConnection;import com.wondertek.controller.MainController;public class FileUtil {public static Vector getList(String path) {FileConnection filecon = null;try {filecon = (FileConnection) (Connector.open(path));if (filecon.exists()) {Vector listVec = new Vector();Enumeration en = filecon.list();while (en.hasMoreElements()) {String name = (String) en.nextElement();if (name.endsWith(".3gp") || name.endsWith(".3GP")) {listVec.addElement(name);}}return listVec;} else {filecon.mkdir();return null;}} catch (Exception e) {e.printStackTrace();return null;} finally {try {if (filecon != null)filecon.close();} catch (IOException e) {e.printStackTrace();}}}public static void deleteFile(String path, String name) {FileConnection fc = null;try {fc = (FileConnection) (Connector.open(path + name));if (fc.exists()) {fc.delete();}} catch (Exception e) {e.printStackTrace();} finally {try {if (fc != null)fc.close();} catch (IOException e) {e.printStackTrace();}}}public static String checkFileName(String fPath, String fName)throws IOException {boolean needCheck = true;FileConnection tmp = null;String newName = fName;int i = 0;while (needCheck) {tmp = (FileConnection) Connector.open(fPath + newName);if (tmp.exists()) {newName = fName.substring(0, fName.indexOf('.')) + "(" + i+ ")" + fName.substring(fName.indexOf('.'));i++;} else {needCheck = false;}}tmp.close();tmp = null;return newName;}public static void writeImage(String name, byte[] image) {FileConnection fc_writeLog = null;DataOutputStream dos = null;try {fc_writeLog = (FileConnection) Connector.open(Consts.LOCAL_DIR+ name);if (!fc_writeLog.exists()) {fc_writeLog.create();}dos = new DataOutputStream(fc_writeLog.openOutputStream());dos.write(image);dos.flush();dos.close();dos = null;fc_writeLog.close();fc_writeLog = null;} catch (IOException e) {e.printStackTrace();} catch (SecurityException e) {e.printStackTrace();} finally {if (dos != null) {try {dos.close();} catch (IOException e) {e.printStackTrace();}dos = null;}if (fc_writeLog != null) {try {fc_writeLog.close();} catch (IOException e) {e.printStackTrace();}fc_writeLog = null;}}}public static void writeLog(String str, String logAttributeName) {FileConnection fc_writeLog = null;InputStream is = null;int pos;DataOutputStream dos = null;try {fc_writeLog = (FileConnection) Connector.open(Consts.LOCAL_DIR+ "log.txt");if (!fc_writeLog.exists()) {fc_writeLog.create();pos = 0;} else {is = fc_writeLog.openInputStream();int size = is.available();byte[] posdata = new byte[size];pos = is.read(posdata);}Calendar cal = Calendar.getInstance();cal.getTime().toString();dos = new DataOutputStream(fc_writeLog.openOutputStream(pos));dos.writeUTF("#[" + cal.getTime().toString() + "|||***"+ logAttributeName + "] : " + str + "\r\n");is.close();is = null;dos.flush();dos.close();dos = null;fc_writeLog.close();fc_writeLog = null;} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();} finally {if (dos != null) {try {dos.close();} catch (IOException e) {e.printStackTrace();}dos = null;}if (fc_writeLog != null) {try {fc_writeLog.close();} catch (IOException e) {e.printStackTrace();}fc_writeLog = null;}}}public static boolean checkDirSize(long fileSize) {long dirOverSize = 0;try {MainController.filecon = (FileConnection) Connector.open(Consts.LOCAL_DIR);if (MainController.filecon.exists()&& MainController.filecon.isDirectory()) {dirOverSize = MainController.filecon.totalSize()- MainController.filecon.usedSize() - 1024 * 1024;}if (fileSize >= dirOverSize) {return false;} else {return true;}} catch (IOException e) {return false;} finally {if (MainController.filecon != null) {try {MainController.filecon.close();} catch (IOException e) {}MainController.filecon = null;}}}}import java.io.InputStream;import java.util.Vector;import javax.microedition.media.Control;import javax.microedition.media.Manager;import javax.microedition.media.MediaException;import javax.microedition.media.Player;import javax.microedition.media.PlayerListener;import javax.microedition.media.control.FramePositioningControl;import javax.microedition.media.control.RateControl;import javax.microedition.media.control.VideoControl;import javax.microedition.media.control.VolumeControl;import com.wondertek.controller.MainController;import com.wondertek.data.download.DownloadController;import com.wondertek.dialog.DialogHudong;import com.wondertek.model.Content;import com.wondertek.util.Consts;import com.wondertek.util.FileUtil;import com.wondertek.util.Util;import com.wondertek.view.VideoPage;public class VideoPlayer extends Thread implements PlayerListener {private byte in_Player_State = 0;public static final byte PLAYER_STATE_ERROR = -1;public static final byte PLAYER_STATE_PREPARE = 0;public static final byte PLAYER_STATE_PREPARED = 1;public static final byte PLAYER_STATE_PLAY = 2;public static final byte PLAYER_STATE_PLAYING = 3;public static final byte PLAYER_STATE_PAUSE = 4;public static final byte PLAYER_STATE_PAUSED = 5;public static final byte PLAYER_STATE_CLOSED = 6;private Player player;private String url;private boolean isRunning;private boolean hasInit;private boolean isBuffer;private boolean isLivePause;private VideoControl videoC;// 图像控制器private VolumeControl volumeC;// 音量控制器private RateControl rc;// 进度控制器private FramePositioningControl fpc;private long totalTime = 0; // 总时间private long currentTime = 0;// 当前时间private long startTime = 0;private long endTime = 0;private boolean isLive = false;private int volumeLevel = 0;private VideoPage videoPage;public long getTotalTime() {return totalTime;}public long getStartTime() {return startTime;}public long getCurrentTime() {return currentTime;}public VideoPlayer(VideoPage videoPage) {this.videoPage = videoPage;init();}public void init() {in_Player_State = PLAYER_STATE_PREPARE;this.isRunning = true;this.hasInit = false;this.isBuffer = false;this.isLivePause = false;totalTime = 0;}public void setEndTime(long endTime) {this.endTime = endTime;}public void setStartTime(long startTime) {this.startTime = startTime;}public void setIslive(boolean islive) {this.isLive = islive;}public void setUrl(String url) {this.url = url;}public String getUrl() {return url;}public boolean isBuffer() {return isBuffer;}public void run() {while (isRunning) {try {Thread.sleep(250);if (!hasInit) {initPlayer();hasInit = true;}if (player != null && in_Player_State > PLAYER_STATE_PREPARED) {if (!isBuffer) {if (in_Player_State == PLAYER_STATE_PLAY) {player.start();in_Player_State = PLAYER_STATE_PLAYING;} else if (in_Player_State == PLAYER_STATE_PAUSE) {player.stop();in_Player_State = PLAYER_STATE_PAUSED;}}}if (isLive && videoPage.getIs_push() == Consts.IS_NOT_PUSH) {if (MainController.getServerTime() > endTime) {if (videoPage.getCurrentContents() != null&& videoPage.getCurrentContents().size() > 0) {Vector contens = videoPage.getCurrentContents();Content nextCon = (Content) contens.elementAt(0);videoPage.setCurrentContent(nextCon);contens.removeElementAt(0);videoPage.setCurrentContents(contens);long liveStartTime = Util.StringToTime(nextCon.getStartTime());startTime = liveStartTime;endTime = Util.StringToTime(nextCon.getEndTime());}}}updatePlayerStatus();} catch (MediaException e) {// FileUtil.writeLog("exception : " + player.getState() + ""// + e.getMessage(), "LOG");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} catch (InterruptedException e) {// FileUtil.writeLog("exception : " + e.getMessage(),// "InterruptedException");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} catch (Exception e) {// FileUtil.writeLog("exception : " + e.getMessage(),// "Exception");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}}}}public synchronized void initPlayer() throws Exception {if (player == null) {if (url.startsWith("resource:")) {InputStream ins = getClass().getResourceAsStream(url.substring(9));String ct = Util.guessContentType(url);player = Manager.createPlayer(ins, ct);} else {player = Manager.createPlayer(url);}}if (player != null) {player.realize();player.prefetch();Control[] controls = player.getControls();for (int i = 0; i < controls.length; i++) {if (controls[i] instanceof VideoControl) {videoC = (VideoControl) controls[i];videoC.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,MainController.currentPage);videoC.setDisplayLocation(0, Consts.HEAD_HEIGHT);videoC.setDisplaySize(Consts.VIDEO_WIDTH,Consts.VIDEO_HEIGHT);videoC.setVisible(false);}if (controls[i] instanceof VolumeControl) {volumeC = (VolumeControl) controls[i];volumeLevel = volumeC.getLevel();}if (controls[i] instanceof RateControl) {rc = (RateControl) controls[i];}if (controls[i] instanceof FramePositioningControl) {fpc = (FramePositioningControl) controls[i];// skipFrame = fpc.mapTimeToFrame(20000);}}// FileUtil.writeLog("CCCCCCCCCCCCCCCCCCCCCC", "LOG");in_Player_State = PLAYER_STATE_PREPARED;player.start();// FileUtil.writeLog("CCCCCCCCCCCCCCCCCCCCCC", "LOG");player.addPlayerListener(this);setVisable(true);in_Player_State = PLAYER_STATE_PLAYING;// FileUtil.writeLog("EEEEEEEEEEEEEEEEEEEEEE", "LOG");}}public byte getIn_Player_State() {return in_Player_State;}public void updatePlayerStatus() {// 更新时间if (player != null && player.getState() >= Player.STARTED) {if (isLive == false) {if (totalTime == 0L || totalTime == -1L) {totalTime = player.getDuration();}if (!isLivePause)currentTime = player.getMediaTime();} else {totalTime = endTime - startTime;currentTime = MainController.getServerTime() - startTime;if (videoPage.getIs_push() == Consts.IS_PUSH) {if (MainController.getServerTime() >= endTime) {closePlayer();}}}} else if (player != null && player.getState() == Player.CLOSED) {totalTime = 0;currentTime = 0;in_Player_State = PLAYER_STATE_CLOSED;}if (videoPage != null)videoPage.repaintProcess();}public void controlVolume(boolean volumeState) {if (volumeC != null) {if (volumeState) {volumeLevel += 5;if (volumeLevel > 100)volumeLevel = 100;} else {volumeLevel -= 5;if (volumeLevel < 0)volumeLevel = 0;}volumeC.setLevel(volumeLevel);}}public void disableVolume() {if (volumeC != null)volumeC.setLevel(0);}public void resumeVolume() {if (volumeC != null)volumeC.setLevel(volumeLevel);}public void setVisable(boolean visable) {if (videoC != null) {videoC.setVisible(visable);}}public void setProgress(boolean flag) {if (totalTime == Player.TIME_UNKNOWN|| currentTime == Player.TIME_UNKNOWN || fpc == null)return;if (flag) {fpc.seek(fpc.mapTimeToFrame(currentTime / 1000+ Consts.PLAY_SEEK_TIME));} else {fpc.seek(fpc.mapTimeToFrame(currentTime / 1000- Consts.PLAY_SEEK_TIME));}}public void rePlay() {videoPage.setPaused(false);hasInit = false;in_Player_State = PLAYER_STATE_PREPARE;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}}public void play() {if (player != null) {in_Player_State = PLAYER_STATE_PLAY;setVisable(true);resumeVolume();} else {in_Player_State = PLAYER_STATE_PREPARE;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}rePlay();}}public void hidePlayer() {isLivePause = true;setVisable(false);disableVolume();}public void resumePlayer() {isLivePause = false;setVisable(true);resumeVolume();}public void stopPlayer() {in_Player_State = PLAYER_STATE_PAUSE;setVisable(false);}public void closePlayer() {isBuffer = false;hasInit = true;if (player != null) {player.deallocate();player = null;}videoPage.setPaused(true);}public void release() {closePlayer();DownloadController.checkDownTask();this.isRunning = false;}public void playerUpdate(Player player, String evt, Object evtData) {if (evt.equals(BUFFERING_STARTED)) {// 开始缓冲isBuffer = true;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(BUFFERING_STOPPED)) {// 缓冲结束isBuffer = false;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(DEVICE_UNAVAILABLE)) {closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(DEVICE_AVAILABLE)) {// in_Player_State = PLAYER_STATE_ERROR;} else if (evt.equals(END_OF_MEDIA)) {closePlayer();in_Player_State = PLAYER_STATE_CLOSED;videoPage.setFinish(true);videoPage.repaint();if (!videoPage.isLocalFile()) {DialogHudong dialogHudong = new DialogHudong();MainController.currentPage.setDialogPage(dialogHudong);MainController.currentPage.setisDialog(true);}}}public int getPlayerProcess() {long playerProcess = 0L;if (isLive) {if (totalTime != 0L)return (int) (currentTime * 134 / totalTime);elsereturn 0;}if (totalTime == 0L || totalTime == -1L) {if (player != null && player.getState() >= Player.STARTED)totalTime = player.getDuration();}if (player != null && totalTime != Player.TIME_UNKNOWN&& totalTime != 0 && currentTime != Player.TIME_UNKNOWN) {playerProcess = currentTime * 134 / totalTime;}return (int) playerProcess;}private String formatNumber(long num, int len, boolean leadingZeros) {StringBuffer ret = new StringBuffer(String.valueOf(num));if (leadingZeros) {while (ret.length() < len) {ret.insert(0, '0');}} else {while (ret.length() < len) {ret.append('0');}}return ret.toString();}private String timeDisplay(long us) {long ts = us / 100000;return formatNumber(ts / 600l, 2, true) + ":"+ formatNumber(((ts % 600) / 10), 2, true);}public String getMediaTimeStr() {try {if (player != null) {return timeDisplay(currentTime);}} catch (IllegalStateException ise) {// thrown when player is closed}return "00:00";}public String getEndTimeStr() {try {if (player != null) {return timeDisplay(totalTime);}} catch (IllegalStateException ise) {// thrown when player is closed}return "00:00";}}import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;import com.tinyline.util.GZIPInputStream;public class Ungzip {public static byte[] inflate(byte gzip[]) throws IOException {ByteArrayInputStream bis = null;ByteArrayOutputStream bos = null;GZIPInputStream gis = null;try {bis = new ByteArrayInputStream(gzip);bos = new ByteArrayOutputStream();gis = new GZIPInputStream(bis);byte[] buf = new byte[512];int len;while ((len = gis.read(buf)) >= 0) {bos.write(buf, 0, len);}return bos.toByteArray();} finally {if (bos != null) {bos.close();bos = null;}if (gis != null) {gis.close();gis = null;}if (bis != null) {bis.close();bis = null;}}}}import java.io.ByteArrayOutputStream;import java.io.DataInputStream;import java.io.IOException;import java.io.InputStream;import javax.microedition.io.Connector;import javax.microedition.io.HttpConnection;import com.wondertek.data.rms.RmsRecord;import com.wondertek.util.Consts;import com.wondertek.util.FileUtil;import com.wondertek.util.Util;public class NetConnector {private String rootUrl;private String host;private String[] url;private int connTimes = 0;public NetConnector(String rootUrl, String host) {this.rootUrl = rootUrl;this.host = host;}public NetConnector() {url = Util.splitDownURL(Consts.serverRoot);if ("true".equals(Consts.isCmwap)) {this.rootUrl = url[0] + "://10.0.0.172" + url[2];this.host = url[1];} else {this.rootUrl = Consts.serverRoot;this.host = "";}}public RmsRecord getDataFromServer(String path, String modifiedTime) {HttpConnection httpConn = null;InputStream is = null;RmsRecord record = new RmsRecord();record.setName(path);try {httpConn = (HttpConnection) Connector.open(rootUrl + path);httpConn.setRequestMethod(HttpConnection.POST);if ("false".equals(Consts.isCmwap)) {httpConn.setRequestProperty("User-Agent", "Nokia6500s-1/2.0");httpConn.setRequestProperty("X-Up-Calling-Line-ID","13816268129");}if (!"".equals(host))httpConn.setRequestProperty("X-Online-Host", host);if (modifiedTime != null)httpConn.setRequestProperty("If-Modified-Since", modifiedTime);if (HttpConnection.HTTP_OK == httpConn.getResponseCode()) {String contentType = httpConn.getHeaderField("Content-Type");if (contentType != null&& (contentType.indexOf("wml") != -1 || contentType.indexOf("WML") != -1)) {record.setFound(false);return record;}String version = httpConn.getHeaderField("Last-Modified");if (version == null)version = "";byte[] data;is = httpConn.openDataInputStream();DataInputStream dis = new DataInputStream(is);int length = (int) httpConn.getLength();if (length == -1) {int chunkSize = 1500;byte[] buffer = new byte[chunkSize];ByteArrayOutputStream baos = new ByteArrayOutputStream();int dataSizeRead = 0;// size of data read from input stream.while ((dataSizeRead = is.read(buffer)) != -1) {baos.write(buffer, 0, dataSizeRead);}data = baos.toByteArray();baos.close();record.setData(data);record.setServerUpdated(true);record.setFound(true);record.setVersion(version);} else if (length == 0) {record.setFound(false);} else {// known lengthdata = new byte[length];dis.readFully(data);record.setData(data);record.setServerUpdated(true);record.setFound(true);record.setVersion(version);}} else if (HttpConnection.HTTP_NOT_MODIFIED == httpConn.getResponseCode()) {record.setServerUpdated(false);record.setFound(true);record.setVersion(modifiedTime);} else {record.setFound(false);}} catch (IOException t) {if (connTimes < 2) {connTimes++;return getDataFromServer(path, modifiedTime);} else {connTimes = 0;return null;}} finally {// Networking done. Clean up the network objectstry {if (is != null)is.close();} catch (Throwable t) {System.out.println("Exception occurred while closing input "+ "stream.");}try {if (httpConn != null)httpConn.close();} catch (Throwable t) {System.out.println("Exception occurred " + t.toString());}}return record;}}import java.io.InputStream;import java.util.Vector;import javax.microedition.media.Control;import javax.microedition.media.Manager;import javax.microedition.media.MediaException;import javax.microedition.media.Player;import javax.microedition.media.PlayerListener;import javax.microedition.media.control.FramePositioningControl;import javax.microedition.media.control.RateControl;import javax.microedition.media.control.VideoControl;import javax.microedition.media.control.VolumeControl;import com.wondertek.controller.MainController;import com.wondertek.data.download.DownloadController;import com.wondertek.dialog.DialogHudong;import com.wondertek.model.Content;import com.wondertek.util.Consts;import com.wondertek.util.FileUtil;import com.wondertek.util.Util;import com.wondertek.view.VideoPage;public class VideoPlayer extends Thread implements PlayerListener {private byte in_Player_State = 0;public static final byte PLAYER_STATE_ERROR = -1;public static final byte PLAYER_STATE_PREPARE = 0;public static final byte PLAYER_STATE_PREPARED = 1;public static final byte PLAYER_STATE_PLAY = 2;public static final byte PLAYER_STATE_PLAYING = 3;public static final byte PLAYER_STATE_PAUSE = 4;public static final byte PLAYER_STATE_PAUSED = 5;public static final byte PLAYER_STATE_CLOSED = 6;private Player player;private String url;private boolean isRunning;private boolean hasInit;private boolean isBuffer;private boolean isLivePause;private VideoControl videoC;// 图像控制器private VolumeControl volumeC;// 音量控制器private RateControl rc;// 进度控制器private FramePositioningControl fpc;private long totalTime = 0; // 总时间private long currentTime = 0;// 当前时间private long startTime = 0;private long endTime = 0;private boolean isLive = false;private int volumeLevel = 0;private VideoPage videoPage;public long getTotalTime() {return totalTime;}public long getStartTime() {return startTime;}public long getCurrentTime() {return currentTime;}public VideoPlayer(VideoPage videoPage) {this.videoPage = videoPage;init();}public void init() {in_Player_State = PLAYER_STATE_PREPARE;this.isRunning = true;this.hasInit = false;this.isBuffer = false;this.isLivePause = false;totalTime = 0;}public void setEndTime(long endTime) {this.endTime = endTime;}public void setStartTime(long startTime) {this.startTime = startTime;}public void setIslive(boolean islive) {this.isLive = islive;}public void setUrl(String url) {this.url = url;}public String getUrl() {return url;}public boolean isBuffer() {return isBuffer;}public void run() {while (isRunning) {try {Thread.sleep(250);if (!hasInit) {initPlayer();hasInit = true;}if (player != null && in_Player_State > PLAYER_STATE_PREPARED) {if (!isBuffer) {if (in_Player_State == PLAYER_STATE_PLAY) {player.start();in_Player_State = PLAYER_STATE_PLAYING;} else if (in_Player_State == PLAYER_STATE_PAUSE) {player.stop();in_Player_State = PLAYER_STATE_PAUSED;}}}if (isLive && videoPage.getIs_push() == Consts.IS_NOT_PUSH) {if (MainController.getServerTime() > endTime) {if (videoPage.getCurrentContents() != null&& videoPage.getCurrentContents().size() > 0) {Vector contens = videoPage.getCurrentContents();Content nextCon = (Content) contens.elementAt(0);videoPage.setCurrentContent(nextCon);contens.removeElementAt(0);videoPage.setCurrentContents(contens);long liveStartTime = Util.StringToTime(nextCon.getStartTime());startTime = liveStartTime;endTime = Util.StringToTime(nextCon.getEndTime());}}}updatePlayerStatus();} catch (MediaException e) {// FileUtil.writeLog("exception : " + player.getState() + ""// + e.getMessage(), "LOG");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} catch (InterruptedException e) {// FileUtil.writeLog("exception : " + e.getMessage(),// "InterruptedException");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} catch (Exception e) {// FileUtil.writeLog("exception : " + e.getMessage(),// "Exception");closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}}}}public synchronized void initPlayer() throws Exception {if (player == null) {if (url.startsWith("resource:")) {InputStream ins = getClass().getResourceAsStream(url.substring(9));String ct = Util.guessContentType(url);player = Manager.createPlayer(ins, ct);} else {player = Manager.createPlayer(url);}}if (player != null) {player.realize();player.prefetch();Control[] controls = player.getControls();for (int i = 0; i < controls.length; i++) {if (controls[i] instanceof VideoControl) {videoC = (VideoControl) controls[i];videoC.initDisplayMode(VideoControl.USE_DIRECT_VIDEO,MainController.currentPage);videoC.setDisplayLocation(0, Consts.HEAD_HEIGHT);videoC.setDisplaySize(Consts.VIDEO_WIDTH,Consts.VIDEO_HEIGHT);videoC.setVisible(false);}if (controls[i] instanceof VolumeControl) {volumeC = (VolumeControl) controls[i];volumeLevel = volumeC.getLevel();}if (controls[i] instanceof RateControl) {rc = (RateControl) controls[i];}if (controls[i] instanceof FramePositioningControl) {fpc = (FramePositioningControl) controls[i];// skipFrame = fpc.mapTimeToFrame(20000);}}// FileUtil.writeLog("CCCCCCCCCCCCCCCCCCCCCC", "LOG");in_Player_State = PLAYER_STATE_PREPARED;player.start();// FileUtil.writeLog("CCCCCCCCCCCCCCCCCCCCCC", "LOG");player.addPlayerListener(this);setVisable(true);in_Player_State = PLAYER_STATE_PLAYING;// FileUtil.writeLog("EEEEEEEEEEEEEEEEEEEEEE", "LOG");}}public byte getIn_Player_State() {return in_Player_State;}public void updatePlayerStatus() {// 更新时间if (player != null && player.getState() >= Player.STARTED) {if (isLive == false) {if (totalTime == 0L || totalTime == -1L) {totalTime = player.getDuration();}if (!isLivePause)currentTime = player.getMediaTime();} else {totalTime = endTime - startTime;currentTime = MainController.getServerTime() - startTime;if (videoPage.getIs_push() == Consts.IS_PUSH) {if (MainController.getServerTime() >= endTime) {closePlayer();}}}} else if (player != null && player.getState() == Player.CLOSED) {totalTime = 0;currentTime = 0;in_Player_State = PLAYER_STATE_CLOSED;}if (videoPage != null)videoPage.repaintProcess();}public void controlVolume(boolean volumeState) {if (volumeC != null) {if (volumeState) {volumeLevel += 5;if (volumeLevel > 100)volumeLevel = 100;} else {volumeLevel -= 5;if (volumeLevel < 0)volumeLevel = 0;}volumeC.setLevel(volumeLevel);}}public void disableVolume() {if (volumeC != null)volumeC.setLevel(0);}public void resumeVolume() {if (volumeC != null)volumeC.setLevel(volumeLevel);}public void setVisable(boolean visable) {if (videoC != null) {videoC.setVisible(visable);}}public void setProgress(boolean flag) {if (totalTime == Player.TIME_UNKNOWN|| currentTime == Player.TIME_UNKNOWN || fpc == null)return;if (flag) {fpc.seek(fpc.mapTimeToFrame(currentTime / 1000+ Consts.PLAY_SEEK_TIME));} else {fpc.seek(fpc.mapTimeToFrame(currentTime / 1000- Consts.PLAY_SEEK_TIME));}}public void rePlay() {videoPage.setPaused(false);hasInit = false;in_Player_State = PLAYER_STATE_PREPARE;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}}public void play() {if (player != null) {in_Player_State = PLAYER_STATE_PLAY;setVisable(true);resumeVolume();} else {in_Player_State = PLAYER_STATE_PREPARE;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}rePlay();}}public void hidePlayer() {isLivePause = true;setVisable(false);disableVolume();}public void resumePlayer() {isLivePause = false;setVisable(true);resumeVolume();}public void stopPlayer() {in_Player_State = PLAYER_STATE_PAUSE;setVisable(false);}public void closePlayer() {isBuffer = false;hasInit = true;if (player != null) {player.deallocate();player = null;}videoPage.setPaused(true);}public void release() {closePlayer();DownloadController.checkDownTask();this.isRunning = false;}public void playerUpdate(Player player, String evt, Object evtData) {if (evt.equals(BUFFERING_STARTED)) {// 开始缓冲isBuffer = true;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(BUFFERING_STOPPED)) {// 缓冲结束isBuffer = false;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(DEVICE_UNAVAILABLE)) {closePlayer();in_Player_State = PLAYER_STATE_ERROR;if (MainController.currentPage instanceof VideoPage) {MainController.currentPage.repaint();}} else if (evt.equals(DEVICE_AVAILABLE)) {// in_Player_State = PLAYER_STATE_ERROR;} else if (evt.equals(END_OF_MEDIA)) {closePlayer();in_Player_State = PLAYER_STATE_CLOSED;videoPage.setFinish(true);videoPage.repaint();if (!videoPage.isLocalFile()) {DialogHudong dialogHudong = new DialogHudong();MainController.currentPage.setDialogPage(dialogHudong);MainController.currentPage.setisDialog(true);}}}public int getPlayerProcess() {long playerProcess = 0L;if (isLive) {if (totalTime != 0L)return (int) (currentTime * 134 / totalTime);elsereturn 0;}if (totalTime == 0L || totalTime == -1L) {if (player != null && player.getState() >= Player.STARTED)totalTime = player.getDuration();}if (player != null && totalTime != Player.TIME_UNKNOWN&& totalTime != 0 && currentTime != Player.TIME_UNKNOWN) {playerProcess = currentTime * 134 / totalTime;}return (int) playerProcess;}private String formatNumber(long num, int len, boolean leadingZeros) {StringBuffer ret = new StringBuffer(String.valueOf(num));if (leadingZeros) {while (ret.length() < len) {ret.insert(0, '0');}} else {while (ret.length() < len) {ret.append('0');}}return ret.toString();}private String timeDisplay(long us) {long ts = us / 100000;return formatNumber(ts / 600l, 2, true) + ":"+ formatNumber(((ts % 600) / 10), 2, true);}public String getMediaTimeStr() {try {if (player != null) {return timeDisplay(currentTime);}} catch (IllegalStateException ise) {// thrown when player is closed}return "00:00";}public String getEndTimeStr() {try {if (player != null) {return timeDisplay(totalTime);}} catch (IllegalStateException ise) {// thrown when player is closed}return "00:00";}}

更多相关文章

  1. Failed to find provider info for com.example.databasetest.pr
  2. AndroidX RecyclerView总结-测量布局
  3. Flutter 和 Android(安卓)互相传递数据的实现
  4. 面试必备:Android(安卓)Activity启动流程源码分析
  5. android 中 Timer 的使用及源码分析
  6. ORMLite简介和增删改查方法的使用
  7. android listview setselection 失效解决办法
  8. Android(安卓)View添加Listener小技巧
  9. android经典面试题集锦

随机推荐

  1. Android赋予内置三方应用应用权限
  2. Android studio和Eclipse使用的简单感受
  3. QGIS on Android
  4. 海康威视视频监控demo 源码+库文件
  5. Android adb(Android Debug Bridge)常用命
  6. [入门三]Android应用开发入门五问
  7. Android 属性动画(Property Animation) 完
  8. Android 中 OnTouch事件的研究
  9. android include 控件详解
  10. Android和Unity混合开发——Activity和Un