android拦截短信并屏蔽系统的Notification

http://blog.csdn.net/wufenglong/archive/2011/03/07/6230310.aspx

 

1.android接收短信时是以广播的方式

 

2.程序只要在自己的Manifest.xml里加有”接收”SMS的权限

 

<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>

 

3.要写个广播接收类

public class smsreceiveandmask extends BroadcastReceiver {
	private String TAG = "smsreceiveandmask";
	@Override
	public void onReceive(Context context, Intent intent) {
		
	}

 

4.Manifest.xml的receiver标签里要加入intent-filter ,action为

<action android:name="android.provider.Telephony.SMS_RECEIVED" />

 

5.重要的是要在这个intent-filter上加上priority优先级,以使自己接收到SMS优先于系统或其它软件

<receiver android:name=".smsreceiveandmask" >
			<intent-filter android:priority="1000"> 
				<action android:name="android.provider.Telephony.SMS_RECEIVED" />
			</intent-filter>
		</receiver>

 

6.当自己的程序接收到要屏蔽的SMS后,用 this.abortBroadcast();来结束广播的继续发给别的程序,这样系统就不会收到短信广播了,Notification也不会有提示了

// 第三步:取消
if (flags_filter) {
	this.abortBroadcast();
}

 

源码如下:

Manifest.xml

< xml version="1.0" encoding="utf-8" >
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.hwttnet.test.smsreceiveandmask" android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="3" />
	<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
	<application android:icon="@drawable/icon" android:label="@string/app_name">
		<receiver android:name=".smsreceiveandmask" >
			<intent-filter android:priority="1000"> 
				<action android:name="android.provider.Telephony.SMS_RECEIVED" />
			</intent-filter>
		</receiver>
	</application>
</manifest>

 

BroadcastReceiver类:

package com.hwttnet.test.smsreceiveandmask;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.util.Log;
public class smsreceiveandmask extends BroadcastReceiver {
	private String TAG = "smsreceiveandmask";
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.v(TAG, ">>>>>>>onReceive start");
		// 第一步、获取短信的内容和发件人
		StringBuilder body = new StringBuilder();// 短信内容
		StringBuilder number = new StringBuilder();// 短信发件人
		Bundle bundle = intent.getExtras();
		if (bundle != null) {
			Object[] _pdus = (Object[]) bundle.get("pdus");
			SmsMessage[] message = new SmsMessage[_pdus.length];
			for (int i = 0; i < _pdus.length; i++) {
				message[i] = SmsMessage.createFromPdu((byte[]) _pdus[i]);
			}
			for (SmsMessage currentMessage : message) {
				body.append(currentMessage.getDisplayMessageBody());
				number.append(currentMessage.getDisplayOriginatingAddress());
			}
			String smsBody = body.toString();
			String smsNumber = number.toString();
			if (smsNumber.contains("+86")) {
				smsNumber = smsNumber.substring(3);
			}
			// 第二步:确认该短信内容是否满足过滤条件
			boolean flags_filter = false;
			if (smsNumber.equals("10086")) {// 屏蔽10086发来的短信
				flags_filter = true;
				Log.v(TAG, "sms_number.equals(10086)");
			}
			// 第三步:取消
			if (flags_filter) {
				this.abortBroadcast();
			}
		}
		Log.v(TAG, ">>>>>>>onReceive end");
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Android事件模型【转】

以前写 android ,对事件的处理没有太深入,只是简单的 onTouchEvent 就 ok 了,现在写的 UI ,很多自定义组件,父 view 和子 view 都需要接收事件,然后处理。如果不弄明白它的事件传递机制,很难拥有好的用户体验。

Touchevent 中,返回值是 true ,则说明消耗掉了这个事件,返回值是 false ,则没有消耗掉,会继续传递下去,这个是最基本的。

在 View 中跟 Touch 相关的事件有 dispatchTouchEvent , interceptTouchEvnet , onTouchEvent 三种。 dispatchTouchEvent 是负责分发事件的,事件从 activity 传递出来之后,最先到达的就是最顶层 view 的 dispatchTouchEvent ,然后它进行分发,如果返回 false ,则交给这个 view 的 interceptTouchEvent 方法来决定是否要拦截这个事件,如果 interceptTouchEvent 返回 true ,也就是拦截掉了,则交给它的 onTouchEvent 来处理,如果 interceptTouchEvent 返回 false ,那么就传递给子 view ,由子 view 的 dispatchTouchEvent 再来开始这个事件的分发。

如果事件传递到某一层的子 view 的 onTouchEvent 上了,这个方法返回了 false ,那么这个事件会从这个 view 往上传递,都是 onTouchEvent 来接收。而如果传递到最上面的 onTouchEvent 也返回 false 的话,这个事件就会“消失”,而且接收不到下一次事件。(我说的一次事件指的是 down 到 up 之间的一系列事件)

注:上半部分为父View,下半部分为子View;

完整的传递流程为:父View->子View->子View的子View->……->子View的子View->子View->父View。

如果整个流程中都没有处理掉这个事件,即所有处理的返回值均为false,则不会再传递下一次事件,因为他会认为你这次的事件阻塞了,没必要给下一次。

onTouchEvent如果不消耗的话,会从子view传递到父view。

转自:http://chroya.iteye.com/blog/668297

  • 大小: 36.2 KB

androidLayoutParams简单说明理解示例

   简单说说 自己对 android LayoutParams的理解吧,xh写不出高级文章是低级写手。

public static class

ViewGroup.LayoutParams

extends Object

java.lang.Object

     android.view.ViewGroup.LayoutParams   //继承关系

以下说明摘自官方文档E文好的可以看看

Class Overview

LayoutParams are used by views to tell their parents how they want to be laid out. See ViewGroup Layout Attributes for a list of all child view attributes that this class supports.

The base LayoutParams class just describes how big the view wants to be for both width and height. For each dimension, it can specify one of:

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)

WRAP_CONTENT, which means that the view wants to be just big enough to enclose its content (plus padding)

an exact number

There are subclasses of LayoutParams for different subclasses of ViewGroup. For example, AbsoluteLayout has its own subclass of LayoutParams which adds an X and Y value.

E文不好看不懂  但是觉得写得啰嗦了

其实这个LayoutParams类是用于child view(子视图) 向 parent view(父视图)传达自己的意愿的一个东西(孩子想变成什么样向其父亲说明)其实子视图父视图可以简单理解成

一个LinearLayout 和 这个LinearLayout里边一个 TextView 的关系 TextView 就算LinearLayout的子视图 child view 。需要注意的是LayoutParams只是ViewGroup的一个内部类 这里边这个也就是ViewGroup里边这个LayoutParams类是 base class 基类 实际上每个不同的ViewGroup都有自己的LayoutParams子类

比如LinearLayout 也有自己的 LayoutParams 大家打开源码看几眼就知道了

myeclipse 怎么查看源码 请看http://byandby.iteye.com/blog/814277

下边来个例子

       //创建一个线性布局
        private LinearLayout mLayout;   
        mLayout = (LinearLayout) findViewById(R.id.layout);   
       //现在我要往mLayout里边添加一个TextView 
      //你可能会想直接在布局文件里边配置不就O 了 那是 但是这里为了说明问题我们用代码实现
       TextView textView = new TextView(Activity01.this);   
            textView.setText("Text View " );
            //这里请不要困惑这里是设置 这个textView的布局 FILL_PARENT WRAP_CONTENT 和在xml文件里边设置是一样的如
   /**<TextView
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Text View"/>*/
 //在xml里边怎么配置高宽大家都会的。
   //第一个参数为宽的设置,第二个参数为高的设置。
            LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(   
                    LinearLayout.LayoutParams.FILL_PARENT,   
                    LinearLayout.LayoutParams.WRAP_CONTENT   
            );   
            //调用addView()方法增加一个TextView到线性布局中
            mLayout.addView(textView, p);   
           //比较简单的一个例子

如果还不能理解下边在来一段直白的说明:

LayoutParams继承于Android.View.ViewGroup.LayoutParams.

LayoutParams相当于一个Layout的信息包,它封装了Layout的位置、高、宽等信息。假设在屏幕上一块区域是由一个Layout占领的,如果将一个View添加到一个Layout中,最好告诉Layout用户期望的布局方式,也就是将一个认可的layoutParams传递进去。

可以这样去形容LayoutParams,在象棋的棋盘上,每个棋子都占据一个位置,也就是每个棋子都有一个位置的信息,如这个棋子在4行4列,这里的“4行4列”就是棋子的LayoutParams。

但LayoutParams类也只是简单的描述了宽高,宽和高都可以设置成三种值:

1,一个确定的值;

2,FILL_PARENT,即填满(和父容器一样大小);

3,WRAP_CONTENT,即包裹住组件就好。

基本就这么多了,不要想的太复杂。

待研究

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");   
			}
		}); 
    }
	
	//长按菜单响应函数
	@Override
	public 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;
		//将数据添加入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/

查手机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);
			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;// 进度控制器
	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);
			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";
	}
}

  • 大小: 98.6 KB
  • 大小: 31.1 KB

UIHandle

http://docs.google.com/View id=dcz49tvn_90cq67qzg3

http://makej2me.iteye.com/blog/629338

http://blog.csdn.net/wong_judy/archive/2010/01/15/5192777.aspx

Activity.dispatchTouchEvent(MotionEvent) -可以在这些事件被分派到窗口之前让Activity截获所有的事件。

ViewGroup.onInterceptTouchEvent(MotionEvent) -让ViewGroup在事件分派到子View之前看到这些事件。

ViewParent.requestDisallowInterceptTouchEvent(boolean) – 让父View不要使用onInterceptTouchEvent(MotionEvent)来截获event.

onLongClick() – 返回一个布尔值表示你是否消耗了该event. 也就是,如果你已经处理了该event, 则它应该停止了,就返回true, 而如果你没有处理它,而是将它留给其它的on-click监听器, 则返回false.

onKey() – 同上.

onTouch() – 返回一个布尔值表示你是否消耗了该event. 该event可以有多个动作. 如果在向下的动作接收时你返回false, 就表示你没有消耗该event, 并且对后续动作也不感兴趣. 也就是说, 后面的手势动作,以及最后的向上动作都将不会再被通知.

键事件永远会被发送到当前获得焦点的View. 它们是从View层次的顶端开始分派, 然后向下直到合适的目的地. 如果你的View现在拥有焦点, 那么你可以从dispatchKeyEvent()方法中看到事件的分派过程. 除了使用veiw之外,你也可以使用你的Activity的onKeyDown()和onKeyUp()方法来获取所有的时间.

注意: Android将首先调用事件处理器, 然后调用合适的默认处理器. 因此, 从这些事件监听器中返回true将使其它监听器和默认处理器失效. 因此在你返回true时要小心.

Android中的Touch event处理方式和其他系统不尽相同。在Android中,一个View加入到一个ViewGroup中,当发生一系列Touch event(即触摸屏幕事件)时,这些事件首先经由ViewGroup中的onInterceptTouchEvent()函数来分派。这个函数决定touch event到底由View处理,还是由ViewGroup处理。它有一个boolean型的返回值,当返回true的时候,则由ViewGroup处理;反之返回false,由View来处理。这本身没有问题。但是这个函数有个特点,那就是如果某一次返回的是true,则从这以后的所有touch event都不需要再经过onInterceptTouchEvent()的分配,而统一都交由ViewGroup处理;如果返回的是false,这次的事件交View处理,下次的event仍然需要由onInterceptTouchEvent()分配,以决定分配给谁

Android/Linux内存监视

http://blog.chinaunix.net/space.php uid=23929779&do=blog&id=85384

Android/Linux 内存监视
 
  • VSS – Virtual Set Size 虚拟耗用内存(包含共享库占用的内存)
  • RSS – Resident Set Size 实际使用物理内存(包含共享库占用的内存)
  • PSS – Proportional Set Size 实际使用的物理内存(比例分配共享库占用的内存)
  • USS – Unique Set Size 进程独自占用的物理内存(不包含共享库占用的内存)

一般来说内存占用大小有如下规律:VSS >= RSS >= PSS >= USS

Android has a tool called procrank (/system/xbin/procrank), which lists out the memory usage of Linux processes in order from highest to lowest usage. The sizes reported per process are VSS, RSS, PSS, and USS

#procrank

—查看当前系统进程的排序(PID,Vss,Rss,Pss,Uss,cmdline)

#top -m 10

—动态查看当前系统进程前10位(PID,CPU,Vss,Rss,cmdline)

ps: 内核查看 #cat /proc/version

Android的3D旋转

       见过没有用opengl的3D动画,看了一下,是用的Camera实现的,内部机制实际上还是opengl,不过大大简化了使用。
       Camera就像一个摄像机,一个物体在原地不动,然后我们带着这个摄像机四处移动,在摄像机里面呈现出来的画面,就会有立体感,就可以从各个角度观看这个物体。
        它有旋转、平移的一系列方法,实际上都是在改变一个Matrix对象,一系列操作完毕之后,我们得到这个Matrix,然后画我们的物体,就可以了。


        常用的API如下:

    rotateX(float degree)  绕着x轴旋转degree个度数
    rotateY(float degree)  绕着y轴旋转degree个度数
    rotateZ(float degree)  绕着z轴旋转degree个度数
    translate(float x,float y,float z)  平移一段距离
    save()和restore()  作用跟Canvas的一样,保存原状态,操作完之后,恢复到原状态。


        下面实现一个简单的图片三维翻转的效果。

package chroya.demo.rotate3d;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.view.MotionEvent;
import android.view.View;

/**
 * 图片三维翻转
 * @author chroya
 */
public class CubeView extends View {
	//摄像机
	private Camera mCamera;
	
	//翻转用的图片
	private Bitmap face;	
	private Matrix mMatrix = new Matrix();
	private Paint mPaint = new Paint();

	private int mLastMotionX, mLastMotionY;
	
	//图片的中心点坐标
	private int centerX, centerY;
	//转动的总距离,跟度数比例1:1
	private int deltaX, deltaY;
	//图片宽度高度
	private int bWidth, bHeight;
	
	public CubeView(Context context) {
		super(context);
		setWillNotDraw(false);
		mCamera = new Camera();	
		mPaint.setAntiAlias(true);
		face = BitmapFactory.decodeResource(getResources(), R.drawable.x);
		bWidth = face.getWidth();
		bHeight = face.getHeight();
		centerX = bWidth>>1;
		centerY = bHeight>>1;
	}	
	
	/**
	 * 转动
	 * @param degreeX
	 * @param degreeY
	 */
	void rotate(int degreeX, int degreeY) {
		deltaX += degreeX;
		deltaY += degreeY;
		
		mCamera.save();
		mCamera.rotateY(deltaX);
		mCamera.rotateX(-deltaY);
		mCamera.translate(0, 0, -centerX);
		mCamera.getMatrix(mMatrix);
		mCamera.restore();	
		//以图片的中心点为旋转中心,如果不加这两句,就是以(0,0)点为旋转中心
		mMatrix.preTranslate(-centerX, -centerY);
		mMatrix.postTranslate(centerX, centerY);		
		mCamera.save();	
		
		postInvalidate();
	}	
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		int x = (int) event.getX();
		int y = (int) event.getY();
		
		switch(event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mLastMotionX = x;
			mLastMotionY = y;
			break;
		case MotionEvent.ACTION_MOVE:
			int dx = x - mLastMotionX;
			int dy = y - mLastMotionY;
			rotate(dx, dy);
			mLastMotionX = x;
			mLastMotionY = y;
			break;
		case MotionEvent.ACTION_UP:
			break;
		}
		return true;
	}
	
	@Override
	public void dispatchDraw(Canvas canvas) {
		super.dispatchDraw(canvas);
		canvas.drawBitmap(face, mMatrix, mPaint);		
	}
}

         注释里面都写的比较清楚了。

         效果如下:

 

 

       可以touch来拖动图片以翻转。这个可以用来做很多事情,比如桌面的立体翻转、立体相册等等。

       源码也附上,见附件。

Android中AVD的使用以及错误处理方法

1.1版本的emulator在设置好环境变量后,直接在命令行中输入 emulator就可以启动了,但是1.5版本中加了个所谓的AVD(Android Virtual Device),AVD就相当于是一个模拟器的,不过你可以利用AVD创建基于不同版本的模拟器,然后使用emulator-avd avdName命令启动不同的模拟器,下面就介绍如何创建AVD:

1.查看当前支持版本(在列出的版本中我们需要记住id值,这个值在第2步中使用):

android list targets

2.创建AVD(最后的2表示创建1.5版本的avd):

android create avd –n avdName –t 2

3.查看是否创建成功(如果成功会显示刚才我们创建的avd信息):

android list avd

4.启动模拟器:

emulator -avd avdName

5.选择启动的皮肤(横向的模拟器)

emulator -avd avdName -skin HVGA-L

6.按Ctrl+F11,可以直接改变模拟器的横纵摆放。

7. 实际创建avd的过程以及错误处理方法

首先创建一个avd,使用命令行方式创建,例如:

D:\android\android-sdk-windows-1.5_r3\tools>android create avd -n avd15 -t 2

Android 1.5 is a basic Android platform.

Do you wish to create a custom hardware profile [no]

Created AVD ‘avd15’ based on Android 1.5

用android list avd命令列出当前的avd:

D:\android\android-sdk-windows-1.5_r3\tools>android list avd

Available Android Virtual Devices:

    Name: avd15

    Path: D:\我的文档\.android\avd\avd15.avd

  Target: Android 1.5 (API level 3)

    Skin: HVGA

注意上面的avd的目录,把上面目录中的\.android的文件夹拷贝到C:\Documents and Settings\Administrator,因为我用的是administrator登陆的,所以拷贝到这个目录下,实际应该拷贝到相应的C:\Documents and Settings\用户名 下,注意用户名要是英文名。

这时候如果用emluator -avd avd15,会得到如下的错误:

emulator: ERROR: no search paths found in this AVD’s configuration.

Weird, the AVD’s config.ini file is malformed. Try re-creating it.

这个错误的原因是C:\Documents and Settings\Administrator\.android\avd目录中的ini文件中包含了中文字符-我的文档,所以要修改这个ini文件-Avd15.ini,修改path为path=C:\Documents and Settings\Administrator\.android\avd\avd15.avd。

这时候,就可以启动emulator了:

D:\android\android-sdk-windows-1.5_r3\tools>emulator -avd avd15

emulator: emulator window was out of view and was recentred

可以看到google的android模拟器了。

运行eclipse中的工程,选择andorid project.会弹出android AVD Error对话框,选择Yes,



然后出现android virtual device manager:



直接点击finish,然后出现 android device chooser对话框:



当前运行的emulator会显示出来,选中它,然后OK.

此时,在emulator中可以显示工程的应用程序。

总结一下:

先启动emulator,然后再运行eclipse中的工程。

android中的LayoutInflater

转自:http://weizhulin.blog.51cto.com/1556324/311450
大家好我们这一节讲的是LayoutInflater的使用,在实际开发种LayoutInflater这个类还是非常有用的,它的作用类似于 findViewById(),
不同点是LayoutInflater是用来找layout下xml布局文件,并且实例化!而findViewById()是找具体xml下的具体 widget控件(如:Button,TextView等)。
为了让大家容易理解我做了一个简单的Demo,主布局main.xml里有一个TextView和一个Button,当点击Button,出现 Dialog,而这个Dialog的布局方式是我们在layout目录下定义的custom_dialog.xml文件(里面左右分布,左边 ImageView,右边TextView)。
效果图如下:
 
下面我将详细的说明Demo的实现过程:
1、新建一个 Android工程,我们命名为LayoutInflaterDemo.
2、修改main.xml布局,里面主要在原来基础上增加了一个Button.代码如下:
 view plaincopy to clipboardprint  
 < 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”   
     >    
 <TextView      
     android:layout_width=”fill_parent”     
     android:layout_height=”wrap_content”     
     android:text=”@string/hello”   
     />    
 <Button    
     android:id=”@+id/button”   
     android:layout_width=”wrap_content”   
     android:layout_height=”wrap_content”   
     android:text=”ShowCustomDialog”   
     />    
 </LinearLayout>   
 
3.定义对话框的布局方式,我们在layout目录下,新建一个名为 custom_dialog.xml文件具体代码如下:
 view plaincopy to clipboardprint  
 < xml version=”1.0″     
 encoding=”utf-8″ >    
 <LinearLayout     
 xmlns:android=”http://schemas.android.com/apk/res/android”   
               android:orientation=”horizontal”   
               android:layout_width=”fill_parent”   
               android:layout_height=”fill_parent”   
               android:padding=”10dp”   
               >    
     <ImageView android:id=”@+id/image”   
                android:layout_width=”wrap_content”   
                android:layout_height=”fill_parent”   
                android:layout_marginRight=”10dp”   
                />    
     <TextView android:id=”@+id/text”   
               android:layout_width=”wrap_content”   
               android:layout_height=”fill_parent”   
               android:textColor=”#FFF”   
               />    
 </LinearLayout>   
 < xml version=”1.0″  
 encoding=”utf-8″ >
 <LinearLayout  
 xmlns:android=”http://schemas.android.com/apk/res/android
               android:orientation=”horizontal”
               android:layout_width=”fill_parent”
               android:layout_height=”fill_parent”
               android:padding=”10dp”
               >
     <ImageView android:id=”@+id/image”
                android:layout_width=”wrap_content”
                android:layout_height=”fill_parent”
                android:layout_marginRight=”10dp”
                />
     <TextView android:id=”@+id/text”
               android:layout_width=”wrap_content”
               android:layout_height=”fill_parent”
               android:textColor=”#FFF”
               />
 </LinearLayout>
 
4.修改主程序LayouInflaterDemo.java代码如下:
 
 view plaincopy to clipboardprint  
 package com.android.tutor;    
 import android.app.Activity;    
 import android.app.AlertDialog;    
 import android.content.Context;    
 import android.os.Bundle;    
 import android.view.LayoutInflater;    
 import android.view.View;    
 import android.view.View.OnClickListener;    
 import android.widget.Button;    
 import android.widget.ImageView;    
 import android.widget.TextView;    
 public class LayoutInflaterDemo extends Activity implements     
 OnClickListener {    
         
     private Button button;    
     public void onCreate(Bundle savedInstanceState) {    
         super.onCreate(savedInstanceState);    
         setContentView(R.layout.main);    
             
         button = (Button)findViewById(R.id.button);    
         button.setOnClickListener(this);    
     }    
     @Override   
     public void onClick(View v) {    
             
         showCustomDialog();    
     }    
         
     public void showCustomDialog()    
     {    
         AlertDialog.Builder builder;    
         AlertDialog alertDialog;    
         Context mContext = LayoutInflaterDemo.this;    
             
         //下面俩种方法都可以    
         ////LayoutInflater inflater = getLayoutInflater();    
         LayoutInflater inflater = (LayoutInflater)     
 mContext.getSystemService(LAYOUT_INFLATER_SERVICE);    
         View layout = inflater.inflate(R.layout.custom_dialog,null);    
         TextView text = (TextView) layout.findViewById(R.id.text);    
         text.setText(“Hello, Welcome to Mr Wei’s blog!”);    
         ImageView image = (ImageView) layout.findViewById(R.id.image);    
     image.setImageResource(R.drawable.icon);    
         builder = new AlertDialog.Builder(mContext);    
         builder.setView(layout);    
         alertDialog = builder.create();    
         alertDialog.show();    
     }    
 }   
5、最后执行之,点击Button,将得到上述效果。