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");
	}
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

待研究

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系统应用调用,intent的使用总结

相当一部分来自文档,希望能有朋友继续完善此贴,以作搜藏。

显示网页:

1. Uri uri = Uri.parse(“http://www.google.com”);
2. Intent it = new Intent(Intent.ACTION_VIEW,uri);
3. startActivity(it);

显示地图:

1. Uri uri = Uri.parse(“geo:38.899533,-77.036476”);
2. Intent it = new Intent(Intent.Action_VIEW,uri);
3. startActivity(it);

路径规划:

1. Uri uri = Uri.parse(“http://maps.google.com/maps f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en”);
2. Intent it = new Intent(Intent.ACTION_VIEW,URI);
3. startActivity(it);

拨打电话:
调用拨号程序

1. Uri uri = Uri.parse(“tel:xxxxxx”);
2. Intent it = new Intent(Intent.ACTION_DIAL, uri);
3. startActivity(it);

1. Uri uri = Uri.parse(“tel.xxxxxx”);
2. Intent it =new Intent(Intent.ACTION_CALL,uri);
3. 要使用这个必须在配置文件中加入<uses-permission id=”android.permission.CALL_PHONE” />

发送SMS/MMS
调用发送短信的程序

1. Intent it = new Intent(Intent.ACTION_VIEW);
2. it.putExtra(“sms_body”, “The SMS text”);
3. it.setType(“vnd.android-dir/mms-sms”);
4. startActivity(it);

发送短信

1. Uri uri = Uri.parse(“smsto:0800000123”);
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. it.putExtra(“sms_body”, “The SMS text”);
4. startActivity(it);

发送彩信

1. Uri uri = Uri.parse(“content://media/external/images/media/23”);
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(“sms_body”, “some text”);
4. it.putExtra(Intent.EXTRA_STREAM, uri);
5. it.setType(“image/png”);
6. startActivity(it);

发送Email

1.
2. Uri uri = Uri.parse(“mailto:xxx@abc.com”);
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. startActivity(it);

1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, “me@abc.com”);
3. it.putExtra(Intent.EXTRA_TEXT, “The email body text”);
4. it.setType(“text/plain”);
5. startActivity(Intent.createChooser(it, “Choose Email Client”));

1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={“me@abc.com”};
3. String[] ccs={“you@abc.com”};
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, “The email body text”);
7. it.putExtra(Intent.EXTRA_SUBJECT, “The email subject text”);
8. it.setType(“message/rfc822”);
9. startActivity(Intent.createChooser(it, “Choose Email Client”));

添加附件

1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_SUBJECT, “The email subject text”);
3. it.putExtra(Intent.EXTRA_STREAM, “file:///sdcard/mysong.mp3”);
4. sendIntent.setType(“audio/mp3”);
5. startActivity(Intent.createChooser(it, “Choose Email Client”));

播放多媒体

1.
2. Intent it = new Intent(Intent.ACTION_VIEW);
3. Uri uri = Uri.parse(“file:///sdcard/song.mp3”);
4. it.setDataAndType(uri, “audio/mp3”);
5. startActivity(it);

1. Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, “1”);
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);

Uninstall 程序

1. Uri uri = Uri.fromParts(“package”, strPackageName, null);
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);

转载自csdn论坛

http://topic.csdn.net/u/20100824/08/d11283b5-b7ab-432a-85bb-4e8e9248d271.html 88915

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的MessageQueue(2)

1.       复习Message Queue的角色

在上一篇里,介绍了AndroidThreadLooperMessage QueueHandler四者间之关系。

先复习如下:

l   UI thread 通常就是main thread,而Android启动程序时(即创建Process)会替它建立一个Message Queue

l   当然需要一个Looper对象,来管理该Message Queue

l   我们可以创建Handler对象来push新消息到Message Queue里;或者接收Looper(Message Queue取出)所送来的消息。

l   线程AHandler对象引用可以传递给别的线程,让别的线程BC等能发送消息来给线程A(存于AMessage Queue)

l   线程AMessage Queue里的消息,只有线程A所属的对象可以处理之

 

 了解了四者间之关系后,在本篇里,就能来思考如何让主线程与子线程之间互相沟通了。包括,子线程push消息到主线程的Message Queue里,并触发主线程去执行某项工作(即执行某个函数)

 

2.  由别的线程发送消息到主线程的Message Queue()

    在上一篇文章里,使用如下程序片段:

// class ac01 extends Activity {

          // ………

              public void onClick(View v) {

                     switch(v.getId()){

                     case 101:

                           t = new myThread();

                           t.start();

                          break;

                     case 102:

                  finish();

                                break;

                     }

           }

//——————————————————             

class EHandler extends Handler {

                   public EHandler(Looper looper) {

                       super(looper);

                   }

                   @Override

                   public void handleMessage(Message msg) {

                      tv.setText((String)msg.obj);

               }

           }

//——————————————————             

class myThread extends Thread{

            private EHandler mHandler;

            public void run() {

                Looper myLooper, mainLooper;

                myLooper = Looper.myLooper();

                mainLooper = Looper.getMainLooper();

                String obj;

                if(myLooper == null){

                       mHandler = new EHandler(mainLooper);

                       obj = “current thread has no looper!”;

                }

                else {

                     mHandler = new EHandler(myLooper);

                     obj = “This is from current thread.”;

                }

                mHandler.removeMessages(0);

                Message m = mHandler.obtainMessage(1, 1, 1, obj);

                mHandler.sendMessage(m);

             }

  }

}

  

这个mHandler定义于myThread类别里,而且由子线程执行指令:      mHandler = new EHandler(mainLooper);

来创建EHandler对象;但是这个mHandler确是属于main线程的(用来存取主线程的MessageQueue),所以指令:

mHandler.sendMessage(m);是将m丢到主线程的MessageQueue里。

此外,我们也可以将mHandler定义于ac01类别里。如下程序范例:

 

//—– Looper_03范例 —–

public class ac01 extends Activity implements OnClickListener {

    private final int WC = LinearLayout.LayoutParams.WRAP_CONTENT;

    private final int FP = LinearLayout.LayoutParams.FILL_PARENT;

    public TextView tv;

    private myThread t;

    private Button btnbtn2;

    EventHandler h;

    Context ctx;

    public void onCreate(Bundle icicle) {

            super.onCreate(icicle);

            ctx = this;

                LinearLayout layout = new LinearLayout(this);

                layout.setOrientation(LinearLayout.VERTICAL);

                              

                btn = new Button(this);

                btn.setId(101);

                btn.setBackgroundResource(R.drawable.heart);

                btn.setText(“test looper”);

                btn.setOnClickListener(this);

                LinearLayout.LayoutParams param =

                    new LinearLayout.LayoutParams(100,50);

                param.topMargin = 10;

                layout.addView(btn, param);

               

                btn2 = new Button(this);

                btn2.setId(102);

                btn2.setBackgroundResource(R.drawable.ok_blue);

                btn2.setText(“exit”);

                btn2.setOnClickListener(this);

                layout.addView(btn2, param);

               

                tv = new TextView(this);

                tv.setTextColor(Color.WHITE);

                tv.setText(“”);

                LinearLayout.LayoutParams param2 =

                   new LinearLayout.LayoutParams(FPWC);

                param2.topMargin = 10;

                layout.addView(tv, param2);

                setContentView(layout);     

               }

          public void onClick(View v) {

        switch(v.getId()){

        case 101:

             h = new EventHandler(Looper.myLooper());

             t = new myThread();

             t.start();

             break;

        case 102:

       finish();

            break;

        }

    }

//————————————————     

public class EventHandler extends Handler {

            public EventHandler(Looper looper) {

                 super(looper);

             }

             @Override

             public void handleMessage(Message msg) {

                      ((Activity)ctx).setTitle((String)msg.obj);

             }

          }

//——————————————————      

class myThread extends Thread{

     public void run() {

            String obj = “from myThread”;

            Message m = h.obtainMessage(1, 1, 1, obj);

            h.sendMessage(m);

      }

  }

}

//——————————————————

 

指令:h = new EventHandler(Looper.myLooper());

h是属于main线程的(用来存取主线程的MessageQueue)。在myThread类别里的指令:h.sendMessage(m);

虽然是由子线程执行该指令,还是将m丢到主线程的MessageQueue里。于是,子线程所执行的run()函数,就顺利将m丢给主线程(Message Queue),并触发了主线程去执行handleMessage()函数了。显示出画面如下:

 

 

 1  

 

上述的指令:

 

          myLooper = Looper.myLooper();

          mainLooper = Looper.getMainLooper();

                ………

          mHandler = new EHandler(mainLooper);

                  ………

          mHandler = new EHandler(myLooper);

                    ………

 

明显地指明mHandler是负责存取哪一个线程的Message Queue。不过,有时候并不需要特别指明。例如上述的onClick()函数和EventHandler类别,可改写为:

 

//—– Looper_03aa 范例 —–

// class ac01 extends Activity {

          // ………

       public void onClick(View v) {

        switch(v.getId()){

        case 101:

             h = new EventHandler();

             t = new myThread();

             t.start();

             break;

        case 102:

              finish();

            break;

        }

    }

//————————————————     

public class EventHandler extends Handler {

             @Override

             public void handleMessage(Message msg) {

                      ((Activity)ctx).setTitle((String)msg.obj);

             }

          }

//——————————————————      

class myThread extends Thread{

     public void run() {

            String obj = “from myThread”;

            Message m = h.obtainMessage(1, 1, 1, obj);

            h.sendMessage(m);

      }

  }

}

 

指令:h = new EventHandler();  就等于:h = new EventHandler(Looper.myLooper());

它建立了当前线程(Current Thread)EventHandler对象。于此,是由main线程执行此指令的,所以此EventHandler对象是用来存取main线程的Message Queue

上述程序将handleMessage()定义于EventHandler类别内,也可以直接定义于ac01类别之内。于是上述程序,也相当于:

 

//—– Looper_03bb 范例 —–

// class ac01 extends Activity {

          // ………

          public void onClick(View v) {

        switch(v.getId()){

        case 101:

             h = new Handler(){

                 public void handleMessage(Message msg) {

                      ((Activity)ctx).setTitle((String)msg.obj);

             }};

              t = new myThread();

             t.start();

             break;

        case 102:

        finish();

            break;

        }

    }

//——————————————————      

class myThread extends Thread{

     public void run() {

            String obj = “from myThread…”;

            Message m = h.obtainMessage(1, 1, 1, obj);

            h.sendMessage(m);

      }

  }

}

 

其执行结果是一样的。

 

转自:http://www.android1.net/Topic.aspx BoardID=11&TopicID=631

android属性系统,SystemProperties的简介—转载

每个属性都有一个名称和值,他们都是字符串格式。属性被大量使用在Android系统中,用来记录系统设置或进程之间的信息交换。属性是在整个系统中全局可见的。每个进程可以get/set属性。
在系统初始化时,Android将分配一个共享内存区来存储的属性。这些是由“init”守护进程完成的,其源代码位于:device/system/init。“init”守护进程将启动一个属性服务。属性服务在“init”守护进程中运行。每一个客户端想要设置属性时,必须连接属性服务,再向其发送信息。属性服务将会在共享内存区中修改和创建属性。任何客户端想获得属性信息,可以从共享内存直接读取。这提高了读取性能。
客户端应用程序可以调用libcutils中的API函数以GET/SET属性信息。libcutils的源代码位于:device/libs/cutils。API函数是:
int property_get(const char *key, char *value, const char *default_value);
int property_set(const char *key, const char *value);
而libcutils又调用libc中的 __system_property_xxx 函数获得共享内存中的属性。libc的源代码位于:device/system/bionic。
属性服务调用libc中的__system_property_init函数来初始化属性系统的共享内存。当启动属性服务时,将从以下文件中加载默认属性:
/ default.prop
/system/build.prop
/system/default.prop
/data/local.prop
属性将会以上述顺序加载。后加载的属性将覆盖原先的值。这些属性加载之后,最后加载的属性会被保持在/data/property中。

 特别属性
如果属性名称以“ro.”开头,那么这个属性被视为只读属性。一旦设置,属性值不能改变。
如果属性名称以“persist.”开头,当设置这个属性时,其值也将写入/data/property。
如果属性名称以“net.”开头,当设置这个属性时,“net.change”属性将会自动设置,以加入到最后修改的属性名。(这是很巧妙的。 netresolve模块的使用这个属性来追踪在net.*属性上的任何变化。)
属性“ ctrl.start ”和“ ctrl.stop ”是用来启动和停止服务。每一项服务必须在/init.rc中定义.系统启动时,与init守护进程将解析init.rc和启动属性服务。一旦收到设置“ ctrl.start ”属性的请求,属性服务将使用该属性值作为服务名找到该服务,启动该服务。这项服务的启动结果将会放入“ init.svc.<服务名>“属性中 。客户端应用程序可以轮询那个属性值,以确定结果。

Android toolbox程序
Android toolbox程序提供了两个工具: setprop和getprop获取和设置属性。其使用方法:
getprop <属性名>
setprop <属性名><<属性值>

Java
在Java应用程序可以使用System.getProperty()和System.setProperty()函数获取和设置属性。

Action
默认情况下,设置属性只会使”init”守护程序写入共享内存,它不会执行任何脚本或二进制程序。但是,您可以将您的想要的实现的操作与init.rc中某个属性的变化相关联.例如,在默认的init.rc中有:

    # adbd on at boot in emulator
    on property:ro.kernel.qemu=1
       start adbd
    on property:persist.service.adb.enable=1
       start adbd
    on property:persist.service.adb.enable=0
       stop adbd

这样,如果你设置persist.service.adb.enable为1 ,”init”守护程序就知道需要采取行动:开启adbd服务。

文章中提到的共享内存就是Android特有的共享方式:ashmen

Ashmem是一个匿名共享内存(Anonymous SHared MEMory)系统,该系统增加了接口因此进程间可以共享具名内存块。举一个例子,系统可以利用Ashmem存储图标,当绘制用户界面的时候多个进程也可以访问。Ashmem优于传统Linux共享内存表现在当共享内存块不再被用的时候,它为Kernel提供一种回收这些共享内存块的手段。如果一个程序尝试访问Kernel释放的一个共享内存块,它将会收到一个错误提示,然后重新分配内存并重载数据。

 

Android 的系统属性包括两部分:文件保存的持久属性和每次开机导入的cache属性。前者主要保存在下面几个文件中:

bionic/libc/include/sys/_system_properties.h

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–>1     #define PROP_SERVICE_NAME “property_service”
2     #define PROP_PATH_RAMDISK_DEFAULT  “/default.prop”
3     #define PROP_PATH_SYSTEM_BUILD     “/system/build.prop”
4     #define PROP_PATH_SYSTEM_DEFAULT   “/system/default.prop”
5     #define PROP_PATH_LOCAL_OVERRIDE   “/data/local.prop”

后者则通过frameworks/base/core/java/android/os/SystemProperties.java的接口定义,

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–> 1     private static native String native_get(String key);
 2     private static native String native_get(String key, String def);
 3     private static native void native_set(String key, String def);
 4     public static void set(String key, String val) {
 5         if (key.length() > PROP_NAME_MAX) {
 6             throw new IllegalArgumentException(key.length >  + PROP_NAME_MAX);
 7         }
 8         if (val != null && val.length() > PROP_VALUE_MAX) {
 9             throw new IllegalArgumentException(val.length >  +
10                 PROP_VALUE_MAX);
11         }
12         native_set(key, val);
13     }

该接口类在初始化运行环境中注册对应的cpp接口android_os_SystemProperties.cpp,实际操作通过JNI调用的是cpp文件对应的接口:

frameworks/base/core/jni/AndroidRuntime.cpp

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–>1     namespace android {
2     extern int register_android_os_SystemProperties(JNIEnv *env);
3     }

frameworks/base/core/jni/android_os_SystemProperties.cpp

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–> 1     static void SystemProperties_set(JNIEnv *env, jobject clazz, jstring keyJ, jstring valJ)
 2     {
 3         int err;
 4         const char* key;
 5         const char* val;
 6         key = env->GetStringUTFChars(keyJ, NULL);
 7         if (valJ == NULL) {
 8             val = “”;       /* NULL pointer not allowed here */
 9         } else {
10             val = env->GetStringUTFChars(valJ, NULL);
11         }
12         err = property_set(key, val);
13         env->ReleaseStringUTFChars(keyJ, key);        
14         if (valJ != NULL) {
15             env->ReleaseStringUTFChars(valJ, val);
16         }
17     }

设置key的value时,需要作鉴权,根据设置程序所在进程的fd获知uid值,比如system server进程可以设置net打头的key,不可以设置gsm打头的key,相关的定义如下:

system/core/include/private/android_filesystem_config.h

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–>1     #define AID_ROOT             0  /* traditional unix root user */
2     #define AID_SYSTEM        1000  /* system server */
3     #define AID_RADIO         1001  /* telephony subsystem, RIL */
4     #define AID_DHCP          1014  /* dhcp client */
5     #define AID_SHELL         2000  /* adb and debug shell user */
6     #define AID_CACHE         2001  /* cache access */
7     #define AID_APP          10000 /* first app user */

system/core/init/property_service.c

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–> 1     #define PERSISTENT_PROPERTY_DIR  “/data/property”
 2     struct {
 3         const char *prefix;
 4         unsigned int uid;
 5     } property_perms[] = {
 6         { net.rmnet0.,    AID_RADIO },
 7         { net.gprs.,      AID_RADIO },
 8         { ril.,           AID_RADIO },
 9         { gsm.,           AID_RADIO },
10         { net.dns,        AID_RADIO },
11         { net.usb0,       AID_RADIO },
12         { net.,           AID_SYSTEM },
13         { dev.,           AID_SYSTEM },
14         { runtime.,       AID_SYSTEM },
15         { hw.,            AID_SYSTEM },
16         { sys.,        AID_SYSTEM },
17         { service.,    AID_SYSTEM },
18         { wlan.,        AID_SYSTEM },
19         { dhcp.,        AID_SYSTEM },
20         { dhcp.,        AID_DHCP },
21         { debug.,        AID_SHELL },
22         { log.,        AID_SHELL },
23         { service.adb.root,    AID_SHELL },
24         { persist.sys.,    AID_SYSTEM },
25         { persist.service.,   AID_SYSTEM },
26         { NULL, 0 }
27     };
28     int property_set(const char *name, const char *value)
29     {
30         property_changed(name, value);
31         return 0;
32     }
33     int start_property_service(void)
34     {
35         int fd;
36 
37         load_properties_from_file(PROP_PATH_SYSTEM_BUILD);
38         load_properties_from_file(PROP_PATH_SYSTEM_DEFAULT);
39         load_properties_from_file(PROP_PATH_LOCAL_OVERRIDE);
40         /* Read persistent properties after all default values have been loaded. */
41         load_persistent_properties();
42 
43         fd = create_socket(PROP_SERVICE_NAME, SOCK_STREAM, 066600);
44         if(fd < 0return 1;
45         fcntl(fd, F_SETFD, FD_CLOEXEC);
46         fcntl(fd, F_SETFL, O_NONBLOCK);
47 
48         listen(fd, 8);
49         return fd;
50     }
51     void handle_property_set_fd(int fd)
52     {
53         switch(msg.cmd) {
54         case PROP_MSG_SETPROP:
55             msg.name[PROP_NAME_MAX1= 0;
56             msg.value[PROP_VALUE_MAX1= 0;
57 
58             if(memcmp(msg.name,ctl.,4== 0) {
59                 if (check_control_perms(msg.value, cr.uid)) {
60                     handle_control_message((char*) msg.name + 4, (char*) msg.value);
61                 } else {
62                     ERROR(sys_prop: Unable to %s service ctl [%s] uid: %d pid:%d\n,
63                             msg.name + 4, msg.value, cr.uid, cr.pid);
64                 }
65             } else {
66                 if (check_perms(msg.name, cr.uid)) {
67                     property_set((char*) msg.name, (char*) msg.value);
68                 } else {
69                     ERROR(sys_prop: permission denied uid:%d  name:%s\n,
70                           cr.uid, msg.name);
71                 }
72             }
73             break;
74 
75         default:
76             break;
77         }
78     }

在开机启动后的init操作中,会执行一个loop循环,当检测到有新的设置时,进入设置流程,鉴权失败会提示相关的异常,如sys_prop: permission denied uid:1000  name:gsm.phone.id

system/core/init/init.c

<!–<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
–> 1     void property_changed(const char *name, const char *value)
 2     {
 3         if (property_triggers_enabled) {
 4             queue_property_triggers(name, value);
 5             drain_action_queue();
 6         }
 7     }
 8     int main(int argc, char **argv)
 9     {
10         parse_config_file(/init.rc);
11         qemu_init();
12         device_fd = device_init();
13         property_init();
14         fd = open(console_name, O_RDWR);
15         property_set_fd = start_property_service();
16         ufds[0].fd = device_fd;
17         ufds[0].events = POLLIN;
18         ufds[1].fd = property_set_fd;
19         ufds[1].events = POLLIN;
20         ufds[2].fd = signal_recv_fd;
21         ufds[2].events = POLLIN;
22         fd_count = 3;
23         for(;;) {
24             if (ufds[0].revents == POLLIN)
25                 handle_device_fd(device_fd);
26 
27             if (ufds[1].revents == POLLIN)
28                 handle_property_set_fd(property_set_fd);
29             if (ufds[3].revents == POLLIN)
30                 handle_keychord(keychord_fd);
31         }
32         return 0;
33     }

学习Android不错的网址

几个不错的Android专栏地址:

安卓bus http://dev.apkbus.com/

http://www.eoeandroid.com/portal.php

第三极:

http://disanji.net/category/android-doc/

moandroid:

http://www.moandroid.com/ page_id=1176

maxlen的专栏:

http://mobile.csdn.net/a/20110209/291511.html

魏祝林的专栏:

http://blog.csdn.net/Android_Tutor/

duguguiyu的深入Android:

http://www.uml.org.cn/j2ee/201004135.asp

我一个哥们的博客,优化Dalvik虚拟机的牛人:

http://blog.csdn.net/tuhuolong/archive/2010/07/26/5766279.aspx

AnroidJNI开发入门系列:

http://my.unix-center.net/~Simon_fu/ p=833

Android游戏开发:

http://mobile.csdn.net/a/20110216/292016.html

Linux下搭建Android开发环境:

http://flysnow.iteye.com/blog/810083

Android的source code:

http://source.android.com/index.html

androidTabHost小结

TabHost是整个Tab的容器,包括两部分,TabWidget和FrameLayout。TabWidget就是每个tab的标签,FrameLayout则是tab内容。

1、如果我们使用extends TabAcitivty,如同ListActivity,TabHost必须设置为@android:id/tabhost

2、TabWidget必须设置android:id为@android:id/tabs

3、FrameLayout需要设置android:id为@android:id/tabcontent

4、参考这儿:http://blog.csdn.net/flowingflying/archive/2011/04/06/6304289.aspx

先自定义一个xml文件:

< xml version="1.0" encoding="utf-8" >
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
	android:id="@android:id/tabhost"
	android:layout_width="fill_parent"
	android:layout_height="fill_parent">
	<LinearLayout
		android:orientation="vertical"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent">
	<FrameLayout
		android:id="@android:id/tabcontent"
		android:layout_width="fill_parent"
		android:layout_height="fill_parent"
		 android:layout_weight="1.0"
		android:paddingBottom="53px"/>
	<TabWidget
		android:id="@android:id/tabs"
		android:layout_alignParentBottom="true"
		android:layout_width="fill_parent"
		android:layout_height="50px" 
		android:visibility="gone"
		android:layout_weight="0.0"/>
		<RadioGroup
			android:gravity="center_vertical"
			android:orientation="horizontal"
			android:id="@+id/main_radio"
			android:background="@drawable/radiogroup_background"
			android:layout_width="fill_parent"
			android:layout_height="50dip"
			android:layout_gravity="bottom">
			<RadioButton
				android:id="@+id/main_index_button"
				android:layout_marginTop="1.0dip"
				android:layout_marginRight="5dip"
				android:text="@string/main_name"
				android:drawableTop="@drawable/unistall"
				style="@style/main_tab_bottom"
				android:background="@drawable/radio_bg"/>
			<RadioButton
				android:id="@+id/main_running_button"
				android:layout_marginTop="1.0dip"
				android:layout_marginRight="5dip"
				android:text="@string/run_manager_name"
				android:drawableTop="@drawable/unistall"
				style="@style/main_tab_bottom"
				android:background="@drawable/radio_bg"/>
			<RadioButton
				android:id="@+id/main_uninstall_button"
				android:layout_marginTop="1.0dip"
				android:text="@string/uninstall_manager_name"
				android:drawableTop="@drawable/unistall"
				style="@style/main_tab_bottom"
				android:background="@drawable/radio_bg"/>
		</RadioGroup>
	</LinearLayout>
</TabHost>

为了让tabHost显示在下方,要将RadioGroup的layout_gravity设置为bottom,再将FrameLayout的layout_weight设置为1,这样就可以将RadioGroup撑到最下方。style=”@style/main_tab_bottom”里面定义了样式文件。

接下来就是在activity中初始化并添加tabhost:

tabHost = (TabHost) findViewById(android.R.id.tabhost);
		tabHost.addTab(Constant.tabHost.newTabSpec("Main")
				.setIndicator(getString(R.string.main_name),null)
				.setContent(new Intent(this, Main.class)));
		tabHost.addTab(Constant.tabHost.newTabSpec("RunManager")
				.setIndicator(getString(R.string.run_manager_name),null)
				.setContent(new Intent(this, RunManager.class)));
		tabHost.addTab(Constant.tabHost.newTabSpec("UninstallManager")
				.setIndicator(getString(R.string.uninstall_manager_name),null)
				.setContent(new Intent(this, UninstallManager.class)));

初始化每个RadioButton并为其添加setOnCheckedChangeListener事件,当点击相应的RadioButton时就可以通过setCurrentTabByTag()方法显示到当前页面。

private void initRadios() {
		((RadioButton) findViewById(R.id.main_index_button))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.main_running_button))
				.setOnCheckedChangeListener(this);
		((RadioButton) findViewById(R.id.main_uninstall_button))
				.setOnCheckedChangeListener(this);
	}
	
	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		if(isChecked){
			switch (buttonView.getId()) {
			case R.id.main_index_button:
				tabHost.setCurrentTabByTag("Main");
				break;
			case R.id.main_running_button:
				tabHost.setCurrentTabByTag("RunManager");
				break;
			case R.id.main_uninstall_button:
				tabHost.setCurrentTabByTag("UninstallManager");
				break;
			}
		}
	}

小结:

1、在一个tabActivity里面嵌套一个tabAcitivity, 如果在子tabActivity里面显示AlertDialog、ProgressDialog的话,就会引发此错误:android.view.WindowManager$BadTokenException: Unable to add window

解决方法:

可以把创建dialog时传递的参数xxx.this改成this.getParent(),其中的xxx为Activity