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); //生成動(dòng)態(tài)數(shù)組,加入數(shù)據(jù) 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和動(dòng)態(tài)數(shù)組對(duì)應(yīng)的元素 SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem,//數(shù)據(jù)源 R.layout.row,//ListItem的XML實(shí)現(xiàn) //動(dòng)態(tài)數(shù)組與ImageItem對(duì)應(yīng)的子項(xiàng) new String[] {"itemImage","itemTitle", "itemText"}, //ImageItem的XML文件里面的一個(gè)ImageView,兩個(gè)TextView ID new int[] {R.id.itemImage,R.id.itemTitle,R.id.itemText} ); //添加并且顯示 list.setAdapter(listItemAdapter); //添加點(diǎn)擊 list.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) { setTitle("點(diǎn)擊第"+arg2+"個(gè)項(xiàng)目"); } }); //添加長(zhǎng)按點(diǎn)擊 list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) { menu.setHeaderTitle("長(zhǎng)按菜單-ContextMenu"); menu.add(0, 0, 0, "彈出長(zhǎng)按菜單0"); menu.add(0, 1, 0, "彈出長(zhǎng)按菜單1"); } }); } //長(zhǎng)按菜單響應(yīng)函數(shù) @Override public boolean onContextItemSelected(MenuItem item) { setTitle("點(diǎn)擊了長(zhǎng)按菜單里面的第"+item.getItemId()+"個(gè)項(xiàng)目"); 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>
/** * 在第一個(gè)字符串中查找匹配字符串的個(gè)數(shù) * @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; } /** * 根據(jù)正則表達(dá)式分割str字符串成為一個(gè)一個(gè)的小的單元! * (實(shí)際使用:在一個(gè)類似語(yǔ)法分析的模塊中發(fā)揮重要作用) * 例如:3+5*4 根據(jù)正則表達(dá)式+-\* 分割成數(shù)組 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; } /** * 檢查是否含有指定的正則表達(dá)式匹配的子串. * @param str 目標(biāo)字符串 * @param regex 正則表達(dá)式,如果正則表達(dá)式含有"^......$"就是查找整個(gè)字符串對(duì)象是否符合正則表達(dá)式. * @return */ public static boolean checkInclude(String str,String regex){ Pattern pattern = Pattern.compile(regex); Matcher matcher = null; matcher = pattern.matcher(str); return matcher.find(); } /** * 方法字符串中符合正則表達(dá)式的子串的集合. * @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()函數(shù)中可以含有數(shù)字,表示查找得到正則表達(dá)式中的goup匹配串. ans.add(matcher.group()); System.out.println("找到匹配的字符串 \"" + matcher.group() + "\" 開始于 " + matcher.start() + " 結(jié)束于 " + matcher.end() + "."); } return ans; }
(1)使用matches方法快速建設(shè)是否表示給定的輸入字符串:Pattern.matches("\\d","1")返回true (2)split(string)使用方法:Pattern.compile(":").split("one:two:three:four:five"); 返回:解析出“one two three four five”單詞 再比如使用數(shù)字作為一個(gè)分割字符串的方法:(注意下面的\\d不是正則表達(dá)式,而是前面加了一個(gè)轉(zhuǎn)義符號(hào)\) Pattern.compile("\\d").split("one9two4three7four1five");也返回相同的結(jié)果。。 (3)在String類中有的幾個(gè)與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)提供了一些正好在輸入字符串中發(fā)現(xiàn)匹配的索引值: public int start():返回之前匹配的開始索引。 public int start(int group):返回之前匹配操作中通過(guò)給定組所捕獲序列的開始索引。 public int end(): 返回最后匹配字符后的偏移量。 public int end(int group): 返回之前匹配操作中通過(guò)給定組所捕獲序列的最后字符之后的偏移量。 研究方法 研究方法(study methods)回顧輸入的字符串,并且返回一個(gè)用于指示是否找到模式的布爾值。 public boolean lookingAt(): 嘗試從區(qū)域開頭處開始,輸入序列與該模式匹配。 public boolean find(): 嘗試地尋找輸入序列中,匹配模式的下一個(gè)子序列。 public boolean find(int start): 重置匹配器,然后從指定的索引處開始,嘗試地尋找輸入序列中,匹配模式的下一個(gè)子序列。 public boolean matches(): 嘗試將整個(gè)區(qū)域與模式進(jìn)行匹配 替換方法 替換方法(replacement methods)用于在輸入的字符串中替換文本有用處的方法。 public Matcher appendReplacement(StringBuffer sb, String replacement):實(shí)現(xiàn)非結(jié)尾處的增加和替換操作。 public StringBuffer appendTail(StringBuffer sb):實(shí)現(xiàn)結(jié)尾處的增加和替換操作。 public String replaceAll(String replacement):使用給定的替換字符串來(lái)替換輸入序列中匹配模式的每一個(gè)子序列。 public String replaceFirst(String replacement):使用給定的替換字符串來(lái)替換輸入序列中匹配模式的第一個(gè)子序列。 public static String quoteReplacement(String s):返回指定字符串的字面值來(lái)替換字符串。這個(gè)方法會(huì)生成一個(gè)字符串,用作 Matcher 的 appendReplacement 方法中的字面值替換 s。所產(chǎn)生的字符串將與作為字面值序列的 s 中的字符序列匹配。斜線(\)和美元符號(hào)($)將不再有特殊意義了。
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; //將數(shù)據(jù)添加入TreeMap for(int i=1;i<=split.length;i++){ if(i<10){ key="0"+i; }else{ key=""+i; } if(split[i-1].equals("0")){//如果為0,不加入map list.add(key); }else{ map.put(key, split[i-1]); } } //打印list for(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(); //打印map Iterator 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 stub String 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/
查手機(jī)UA
UA=<%=request.getHeader("User-Agent")%>
或試試下面這個(gè):
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組件應(yīng)注意幾點(diǎn)小問(wèn)題
http://hi.baidu.com/%CD%F2%B4%BA%C0%F6/blog/item/e8a373519071de2c42a75b92.html
利用Jakarta commons fileupload組件實(shí)現(xiàn)多 文件上傳
http://blog.csdn.net/hbcui1984/archive/2007/05/25/1625754.aspx
對(duì)commons fileupload組件的簡(jiǎn)單封裝
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 操作 模板基類設(shè)計(jì)
http://www.iteye.com/topic/348531
Hibernate 數(shù)據(jù)庫(kù)操作 模板基類 實(shí)現(xiàn)類GenericHibernateDao
http://www.iteye.com/topic/384199
應(yīng)用Hibernate3的DetachedCriteria實(shí)現(xiàn)分頁(yè)查詢
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
好用的復(fù)選樹源碼改進(jìn)版
http://cxlh.iteye.com/blog/419010
getScheme()方法返回請(qǐng)求的計(jì)劃,比如http,https或者ftp.
getServerName()方法返回被發(fā)送請(qǐng)求的服務(wù)器的主機(jī)名
getServerPort()方法返回被發(fā)送請(qǐng)求的端口號(hào)。
getContextPath()返回請(qǐng)求地址的根目錄,以"/"開關(guān),但不是以"/"結(jié)尾。
一個(gè)常用的獲得服務(wù)器地址的連接字符串是:
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
1:先來(lái)個(gè)簡(jiǎn)單的
“用戶登錄一次后,一個(gè)月內(nèi)不需要再次登錄,請(qǐng)給出實(shí)現(xiàn)方法,用cookie實(shí)現(xiàn)"
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('輸入出錯(cuò)!')</script>"); 20. } 21. }
2:請(qǐng)問(wèn)如何禁止某一固定IP 訪問(wèn)論壇,列出您所知道的方法,可以編程實(shí)現(xiàn)也可以采用其他途徑! 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;// 進(jìn)度控制器 private FramePositioningControl fpc; private long totalTime = 0; // 總時(shí)間 private long currentTime = 0;// 當(dāng)前時(shí)間 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() {// 更新時(shí)間 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)) {// 緩沖結(jié)束 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); else return 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 length data = 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 objects try { 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;// 進(jìn)度控制器 private FramePositioningControl fpc; private long totalTime = 0; // 總時(shí)間 private long currentTime = 0;// 當(dāng)前時(shí)間 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() {// 更新時(shí)間 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)) {// 緩沖結(jié)束 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); else return 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"; } }
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
