posts - 93,  comments - 2,  trackbacks - 0
 
----------------------------------------------一.WEB项目的执行流程---------------------------------
1.web项目的运行流程大致如下:    
    启动tomcat,先到web.xml里面查看<context-param><listener><filter><servlet>等等几个tag,查看里面的配置,查找相应的配置文件。
如下列文件所示:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>SpringMVC12</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
 
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:config/springAnnotation-*.xml</param-value>
  </context-param>
 
 
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
 
  <servlet>
   <servlet-name>springMVC</servlet-name>
   <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath*:config/springAnnotation-servlet.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
 
  <filter>
  <filter-name>encodingFilter</filter-name>
  <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  <init-param>
   <param-name>encoding</param-name>
   <param-value>UTF-8</param-value>
  </init-param>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 <!-- encoding filter for jsp page -->
 <filter-mapping>
  <filter-name>encodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>
 
  <servlet-mapping>
   <servlet-name>springMVC</servlet-name>
   <url-pattern>/</url-pattern>
  </servlet-mapping>
 
  <filter>
    <filter-name>openSession</filter-name>
    <filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
  </filter>
 
  <filter-mapping>
   <filter-name>openSession</filter-name>
   <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

首先查看那几个标签,找到对应的配置文件,如<context-param>中配置的classpath*:config/springAnnotation-*.xml。


---------------------------------------2.到配置文件查看相关信息----------------------------------------------
(1)<context-param>里的classpath*:config/springAnnotation-*.xml,即在config目录下匹配springAnnotation-*.xml的文件



(1.1)查看springAnnotation-core.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
 
 <import resource="classpath*:com/zyh/web/controller/spring/springAnnotation-import.xml"/>
</beans>

对应的路径如下com/zyh/web/controller/spring/springAnnotation-import.xml
(1.2)查看springAnnotation-import.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
 <bean id="userDao" class="com.zyh.web.controller.dao.UserDAO">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
 
 <bean id="userManagerBase" class="com.zyh.web.controller.service.UserManager">
  <property name="userDao" ref="userDao"></property>
 </bean>
 
 <bean id="userManager" parent="transactionBese">
  <property name="target" ref="userManagerBase"></property>
 </bean>
 
</beans>

对应关于就已经配置在容器里面了。
(2.1)查看springAnnotation-hibernate.xml(配置数据源,sessionFactory,和事物)

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
 <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost/test1?useUnicode=true"/>
  <property name="username" value="root"/>
  <property name="password" value="root"/>
 </bean>
 
 <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hiberante.format_sql">true</prop>
   </props>
  </property>
  <property name="configLocations">
   <list>
    <value>
     classpath*:com/zyh/web/controller/hibernate/hibernate.cfg.test.xml
    </value>
   </list>
  </property>
 </bean>
 
 <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
 </bean>
 
 <bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
  <property name="transactionManager" ref="transactionManager"></property>
  <property name="transactionAttributes">
   <props>
    <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="get*">PROPAGATION_NEVER</prop>
   </props>
  </property>
 </bean>
</beans>

 配置的对应的 classpath*:com/zyh/web/controller/hibernate/hibernate.cfg.test.xml
    

(3)springAnnotation-servlet.xml,内容如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans
 xmlns:context="http://www.springframework.org/schema/context
 xmlns:p="http://www.springframework.org/schema/p
 xmlns:mvc="http://www.springframework.org/schema/mvc
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
     <!-- 注解扫描包 -->
 <context:component-scan base-package="com.zyh.web.controller" />
 <!-- 开启注解 -->
 
 <mvc:annotation-driven/>
 
 <!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
 <bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
 <!-- 静态资源访问 -->
  <mvc:resources location="/img/" mapping="/img/**"/> 
  <mvc:resources location="/js/" mapping="/js/**"/>  
 

 <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/"></property>
  <property name="suffix" value=".jsp"></property>
 </bean>
 
 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8" />
       <property name="maxUploadSize" value="10485760000" />
       <property name="maxInMemorySize" value="40960" />
 </bean>
 </beans> 



<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans
xmlns:context="http://www.springframework.org/schema/context
xmlns:p="http://www.springframework.org/schema/p
xmlns:mvc="http://www.springframework.org/schema/mvc
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance
xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context.xsd 
      http://www.springframework.org/schema/mvc 
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
     <!-- 注解扫描包 -->
<context:component-scan base-package="com.zyh.web.controller" />
<!-- 开启注解 -->

<mvc:annotation-driven/>

<!-- <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"></bean> -->
<!-- 静态资源访问 -->
  <mvc:resources location="/img/" mapping="/img/**"/> 
  <mvc:resources location="/js/" mapping="/js/**"/>  

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/"></property>
  <property name="suffix" value=".jsp"></property>
</bean>

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8" />
       <property name="maxUploadSize" value="10485760000" />
       <property name="maxInMemorySize" value="40960" />
</bean>
</beans> 


springAnnotation-hibernate.xml<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/context/WEB-INF/contextInclude.xml">
]>

<beans>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
  <property name="url" value="jdbc:mysql://localhost/test1?useUnicode=true"/>
  <property name="username" value="root"/>
  <property name="password" value="root"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"/>
  <property name="hibernateProperties">
   <props>
    <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
    <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hiberante.format_sql">true</prop>
   </props>
  </property>
  <property name="configLocations">
   <list>
    <value>
     classpath*:com/zyh/web/controller/hibernate/hibernate.cfg.test.xml
    </value>
   </list>
  </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
  <property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean id="transactionBese" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
  <property name="transactionManager" ref="transactionManager"></property>
  <property name="transactionAttributes">
   <props>
    <prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
    <prop key="get*">PROPAGATION_NEVER</prop>
   </props>
  </property>
</bean>
</beans>

这个写的有点乱,理清思路,其实很简单,就是配置spring容器,里面扫描了所有的bean及一些依赖关系,hibernate配置数据源建立数据库连接,SessionFactory用于管理数据库,还有就是Springmvc用于控制视图与后台之间的页面转向,传递数据,发送请求。
配置工作就到此结束,然后就是写bean,dao,service,control与联系配置文件的对应关系,实际开发中当然不会把配置文件都写好才来写java代码。我的做法是同时进行,漏了就相应的加上。

-----------------------------------------------------------3对应的实现--------------------------------------
3.1 为了简单,我们建立一个单表的添删改查,就一个对象吧User,对应的表T_User,里面有userName和age两个属性,当然还要建立一个主键id,如下列代码所示:
com.zyh.web.controller.entity.User

package com.zyh.web.controller.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="T_USER")
public class User {

 @GeneratedValue(generator = "system-uuid") 
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(length=32)
 @Id
 private String id;
 
 @Column(length=32)
 private String userName;
 
 @Column(length=32)
 private String age;
 
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }

}
3.2 dao层结构如下:接口IUserDAO与实现类UserDAO,我们实现添删改查,查询包括一个User和所以User
com.zyh.web.controller.dao.IUserDAO

package com.zyh.web.controller.dao;

import java.util.List;

import com.zyh.web.controller.entity.User;

public interface IUserDAO {

 public void addUser(User user);
 
 public List<User> getAllUser();
 
 public User getUser(String id);
 
 public boolean delUser(String id);
 
 public boolean updateUser(User user);
}
实现类UserDAO:

package com.zyh.web.controller.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.zyh.web.controller.entity.User;

public class UserDAO implements IUserDAO {

 private SessionFactory sessionFactory;
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  sessionFactory.getCurrentSession().save(user);
 }

 @Override
 public List<User> getAllUser() {
  // TODO Auto-generated method stub
  String hql = "from User";
  Query query =  sessionFactory.getCurrentSession().createQuery(hql);
  return query.list();
 }

 @Override
 public User getUser(String id) {
  // TODO Auto-generated method stub
  String hql = "from User u where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, id);
  return (User) query.uniqueResult();
 }

 @Override
 public boolean delUser(String id) {
  // TODO Auto-generated method stub
  String hql = "delete User u where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, id);
  return (query.executeUpdate()>0);
 }

 @Override
 public boolean updateUser(User user) {
  // TODO Auto-generated method stub
  String hql = "update User u set u.userName=?,u.age=? where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, user.getUserName());
  query.setString(1, user.getAge());
  query.setString(2, user.getId());
  return (query.executeUpdate()>0);
 }

}

3.3 service层结构如下:接口IUserManager与实现类UserManager,我们实现添删改查,查询包括一个User和所以User
com.zyh.web.controller.service.IUserManager

package com.zyh.web.controller.service;

import java.util.List;

import com.zyh.web.controller.entity.User;

public interface IUserManager {
 
 public void addUser(User user);
 
 public List<User> getAllUser();
 
 public boolean delUser(String id);
 
 public User getUser(String id);
 
 public boolean updateUser(User user);
}
实现类UserManager.java

package com.zyh.web.controller.service;

import java.util.List;

import com.zyh.web.controller.dao.IUserDAO;
import com.zyh.web.controller.entity.User;

public class UserManager implements IUserManager {
 
 private IUserDAO userDao;
 
 public void setUserDao(IUserDAO userDao) {
  this.userDao = userDao;
 }

 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  userDao.addUser(user);
 }

 @Override
 public List<User> getAllUser() {
  // TODO Auto-generated method stub
  return userDao.getAllUser();
 }

 @Override
 public boolean delUser(String id) {
  // TODO Auto-generated method stub
  return userDao.delUser(id);
 }

 @Override
 public User getUser(String id) {
  // TODO Auto-generated method stub
  return userDao.getUser(id);
 }

 @Override
 public boolean updateUser(User user) {
  // TODO Auto-generated method stub
  return userDao.updateUser(user);
 }

}

4.Control层结构如下:实现类UserController.java,代码如下:

package com.zyh.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zyh.web.controller.entity.User;
import com.zyh.web.controller.service.IUserManager;

@Controller
@RequestMapping("/user")
public class UserController {
 @Resource(name="userManager")
 private IUserManager userManager;
 
 @RequestMapping("/toAddUser")
 public String toAddUser(){
  return "/addUser";
 }
 
 @RequestMapping("/addUser")
 public String addUser(User user){
  userManager.addUser(user);
  return "redirect:/user/getAllUser";
 }
 
 @RequestMapping("/getAllUser")
 public String getAllUser(HttpServletRequest request){
  List<User> user = userManager.getAllUser();
  request.setAttribute("user", user);
  return "/userManager";
 }
 
 @RequestMapping("/delUser")
 public void delUser(String id,HttpServletResponse response){
  String result = "{\"result\":\"error\"}";
  if(userManager.delUser(id)){
   result = "{\"result\":\"success\"}";
  }
  response.setContentType("application/json");
  PrintWriter pw;
  try {
   pw = response.getWriter();
   pw.write(result);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 @RequestMapping("/getUser")
 public String getUser(String id,HttpServletRequest request){
  User user = userManager.getUser(id);
  request.setAttribute("user", user);
  return "editUser";
 }
 
 @RequestMapping("/updateUser")
 public String updateUser(User user,HttpServletRequest request){
  if(userManager.updateUser(user)){
   userManager.getUser(user.getId());
   request.setAttribute("user", user);
   return "/editUser";
  }else{
   return "/error";
  }
 }
}

--

 
--

package com.zyh.web.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.zyh.web.controller.entity.User;
import com.zyh.web.controller.service.IUserManager;

@Controller
@RequestMapping("/user")
public class UserController {
 @Resource(name="userManager")
 private IUserManager userManager;
 
 @RequestMapping("/toAddUser")
 public String toAddUser(){
  return "/addUser";
 }
 
 @RequestMapping("/addUser")
 public String addUser(User user){
  userManager.addUser(user);
  return "redirect:/user/getAllUser";
 }
 
 @RequestMapping("/getAllUser")
 public String getAllUser(HttpServletRequest request){
  List<User> user = userManager.getAllUser();
  request.setAttribute("user", user);
  return "/userManager";
 }
 
 @RequestMapping("/delUser")
 public void delUser(String id,HttpServletResponse response){
  String result = "{\"result\":\"error\"}";
  if(userManager.delUser(id)){
   result = "{\"result\":\"success\"}";
  }
  response.setContentType("application/json");
  PrintWriter pw;
  try {
   pw = response.getWriter();
   pw.write(result);
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }
 
 @RequestMapping("/getUser")
 public String getUser(String id,HttpServletRequest request){
  User user = userManager.getUser(id);
  request.setAttribute("user", user);
  return "editUser";
 }
 
 @RequestMapping("/updateUser")
 public String updateUser(User user,HttpServletRequest request){
  if(userManager.updateUser(user)){
   userManager.getUser(user.getId());
   request.setAttribute("user", user);
   return "/editUser";
  }else{
   return "/error";
  }
 }
}

 

 

 

 



 

package com.zyh.web.controller.service;

import java.util.List;

import com.zyh.web.controller.dao.IUserDAO;
import com.zyh.web.controller.entity.User;

public class UserManager implements IUserManager {
 
 private IUserDAO userDao;
 
 public void setUserDao(IUserDAO userDao) {
  this.userDao = userDao;
 }

 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  userDao.addUser(user);
 }

 @Override
 public List<User> getAllUser() {
  // TODO Auto-generated method stub
  return userDao.getAllUser();
 }

 @Override
 public boolean delUser(String id) {
  // TODO Auto-generated method stub
  return userDao.delUser(id);
 }

 @Override
 public User getUser(String id) {
  // TODO Auto-generated method stub
  return userDao.getUser(id);
 }

 @Override
 public boolean updateUser(User user) {
  // TODO Auto-generated method stub
  return userDao.updateUser(user);
 }

}

--

package com.zyh.web.controller.service;

import java.util.List;

import com.zyh.web.controller.entity.User;

public interface IUserManager {
 
 public void addUser(User user);
 
 public List<User> getAllUser();
 
 public boolean delUser(String id);
 
 public User getUser(String id);
 
 public boolean updateUser(User user);
}

 

--
3.2 dao层结构如下:接口IUserDAO与实现类UserDAO,我们实现添删改查,查询包括一个User和所以User
com.zyh.web.controller.dao.IUserDAO
--

package com.zyh.web.controller.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;

import com.zyh.web.controller.entity.User;

public class UserDAO implements IUserDAO {

 private SessionFactory sessionFactory;
 public void setSessionFactory(SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 @Override
 public void addUser(User user) {
  // TODO Auto-generated method stub
  sessionFactory.getCurrentSession().save(user);
 }

 @Override
 public List<User> getAllUser() {
  // TODO Auto-generated method stub
  String hql = "from User";
  Query query =  sessionFactory.getCurrentSession().createQuery(hql);
  return query.list();
 }

 @Override
 public User getUser(String id) {
  // TODO Auto-generated method stub
  String hql = "from User u where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, id);
  return (User) query.uniqueResult();
 }

 @Override
 public boolean delUser(String id) {
  // TODO Auto-generated method stub
  String hql = "delete User u where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, id);
  return (query.executeUpdate()>0);
 }

 @Override
 public boolean updateUser(User user) {
  // TODO Auto-generated method stub
  String hql = "update User u set u.userName=?,u.age=? where u.id=?";
  Query query = sessionFactory.getCurrentSession().createQuery(hql);
  query.setString(0, user.getUserName());
  query.setString(1, user.getAge());
  query.setString(2, user.getId());
  return (query.executeUpdate()>0);
 }

}

 

 

 




 

package com.zyh.web.controller.dao;

import java.util.List;

import com.zyh.web.controller.entity.User;

public interface IUserDAO {

 public void addUser(User user);
 
 public List<User> getAllUser();
 
 public User getUser(String id);
 
 public boolean delUser(String id);
 
 public boolean updateUser(User user);
}

--

package com.zyh.web.controller.entity;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name="T_USER")
public class User {

 @GeneratedValue(generator = "system-uuid") 
    @GenericGenerator(name = "system-uuid", strategy = "uuid")
    @Column(length=32)
 @Id
 private String id;
 
 @Column(length=32)
 private String userName;
 
 @Column(length=32)
 private String age;
 
 public String getId() {
  return id;
 }
 public void setId(String id) {
  this.id = id;
 }
 public String getUserName() {
  return userName;
 }
 public void setUserName(String userName) {
  this.userName = userName;
 }
 public String getAge() {
  return age;
 }
 public void setAge(String age) {
  this.age = age;
 }

}

--


 

 

 

 

 

 


 

posted @ 2013-06-01 10:49 Terry Zou 阅读(4145) | 评论 (0)编辑 收藏

/**
* @param 将字节数组转换为ImageView可调用的Bitmap对象

 * @param bytes

 * @param opts

 * @return Bitmap

 */

 public static Bitmap getPicFromBytes(byte[] bytes, BitmapFactory.Options opts) {

     if (bytes != null)

        if (opts != null
             return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,  opts); 
        else

            return BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
     return null;

}

这里我们主要来介绍一个BitmapFactory.Options这个类
    

BitmapFactory.Options这个类的详解如下:

public Bitmap

inBitmap

If set, decode methods that take the Options object will attempt to reuse this bitmap when loading content.

public int

inDensity

The pixel density to use for the bitmap.

public boolean

inDither

If dither is true, the decoder will attempt to dither the decoded image.

public boolean

inInputShareable

This field works in conjuction with inPurgeable.

public boolean

inJustDecodeBounds

If set to true, the decoder will return null (no bitmap), but the out…

public boolean

inMutable

If set, decode methods will always return a mutable Bitmap instead of an immutable one.

public boolean

inPreferQualityOverSpeed

If inPreferQualityOverSpeed is set to true, the decoder will try to decode the reconstructed image to a higher quality even at the expense of the decoding speed.

publicBitmap.Config

inPreferredConfig

If this is non-null, the decoder will try to decode into this internal configuration.

public boolean

inPurgeable

If this is set to true, then the resulting bitmap will allocate its pixels such that they can be purged if the system needs to reclaim memory.

public int

inSampleSize

If set to a value > 1, requests the decoder to subsample the original image, returning a smaller image to save memory.

public boolean

inScaled

When this flag is set, if inDensity and inTargetDensity are not 0, the bitmap will be scaled to match inTargetDensity when loaded, rather than relying on the graphics system scaling it each time it is drawn to a Canvas.

public int

inScreenDensity

The pixel density of the actual screen that is being used.

public int

inTargetDensity

The pixel density of the destination this bitmap will be drawn to.

public byte[]

inTempStorage

Temp storage to use for decoding.

public boolean

mCancel

Flag to indicate that cancel has been called on this object.

public int

outHeight

The resulting height of the bitmap, set independent of the state of inJustDecodeBounds.

public String

outMimeType

If known, this string is set to the mimetype of the decoded image.

public int

outWidth

The resulting width of the bitmap, set independent of the state of inJustDecodeBounds.

这个表格是从android sdk文档里摘出来的,简单看一下说明就明白是什么意思了。
下面我们回到我们的主题上来:怎样获取图片的大小?
思路很简单:
首先我们把这个图片转成Bitmap,然后再利用Bitmap的getWidth()和getHeight()方法就可以取到图片的宽高了。
新问题又来了,在通过BitmapFactory.decodeFile(String path)方法将突破转成Bitmap时,遇到大一些的图片,我们经常会遇到OOM(Out Of Memory)的问题。怎么避免它呢?
这就用到了我们上面提到的BitmapFactory.Options这个类。

BitmapFactory.Options这个类,有一个字段叫做 inJustDecodeBounds 。SDK中对这个成员的说明是这样的:
If set to true, the decoder will return null (no bitmap), but the out…
也就是说,如果我们把它设为true,那么BitmapFactory.decodeFile(String path, Options opt)并不会真的返回一个Bitmap给你,它仅仅会把它的宽,高取回来给你,这样就不会占用太多的内存,也就不会那么频繁的发生OOM了。
示例代码如下:

  1. BitmapFactory.Options options = new BitmapFactory.Options();
  2. options.inJustDecodeBounds = true;
  3. Bitmap bmp = BitmapFactory.decodeFile(path, options);
  4. /* 这里返回的bmp是null */

复制代码

这段代码之后,options.outWidth 和 options.outHeight就是我们想要的宽和高了。

有了宽,高的信息,我们怎样在图片不变形的情况下获取到图片指定大小的缩略图呢?
比如我们需要在图片不变形的前提下得到宽度为200的缩略图。
那么我们需要先计算一下缩放之后,图片的高度是多少

  1. /* 计算得到图片的高度 */
  2. /* 这里需要主意,如果你需要更高的精度来保证图片不变形的话,需要自己进行一下数学运算 */
  3. int height = options.outHeight * 200 / options.outWidth;
  4. options.outWidth = 200;
  5. options.outHeight = height;
  6. /* 这样才能真正的返回一个Bitmap给你 */
  7. options.inJustDecodeBounds = false;
  8. Bitmap bmp = BitmapFactory.decodeFile(path, options);
  9. image.setImageBitmap(bmp);

复制代码

这样虽然我们可以得到我们期望大小的ImageView
但是在执行BitmapFactory.decodeFile(path, options);时,并没有节约内存。
要想节约内存,还需要用到BitmapFactory.Options这个类里的 inSampleSize 这个成员变量。
我们可以根据图片实际的宽高和我们期望的宽高来计算得到这个值。

  1. inSampleSize = options.outWidth / 200;

另外,为了节约内存我们还可以使用下面的几个字段:

  1. options.inPreferredConfig = Bitmap.Config.ARGB_4444;    // 默认是Bitmap.Config.ARGB_8888
  2. /* 下面两个字段需要组合使用 */
  3. options.inPurgeable = true;
  4. options.inInputShareable = true;

    

posted @ 2013-05-29 11:36 Terry Zou 阅读(2822) | 评论 (0)编辑 收藏
1) 用第一种方式的弊端:

         a.   会将原来系统中的对应的apk覆盖掉,所以,最好先备份出来一份,用如下命令:

               adb pull /system/app/xxxx.apk    /home/

         b.   有时候,会出现如下形式的错误信息:

               failed to copy '/home/SoundRecorder.apk' to '/system/app/SoundRecorder.apk': Read-only file system

              很明显,/system/app目录是只读的,不能将文件push到这个目录下。

             解决方法,用直接安装的方式进行安装,如下:

                adb install -r /home/SoundRecorder.apk     //注: -r 表示强制安装
               这样,会将应用程序安装到 /data/local/tmp/ 目录下。

   2) 用第二种方式的话,设备中不回保存apk文件,如果以后删除了这个应用,就要重新找到对应的apk,才能安装。
posted @ 2013-05-29 09:21 Terry Zou 阅读(364) | 评论 (0)编辑 收藏
<context-param>的作用:
web.xml的配置中<context-param>配置作用
1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml.读两个节点: <listener></listener> 和 <context-param></context-param>
2.紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文.
3.容器将<context-param></context-param>转化为键值对,并交给ServletContext.
4.容器创建<listener></listener>中的类实例,即创建监听.
5.在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得ServletContext = ServletContextEvent.getServletContext();
context-param的值 = ServletContext.getInitParameter("context-param的键");
6.得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早.
换句话说,这个时候,你对<context-param>中的键值做的操作,将在你的WEB项目完全启动之前被执行.
7.举例.你可能想在项目启动之前就打开数据库.
那么这里就可以在<context-param>中设置数据库的连接方式,在监听类中初始化数据库的连接.
8.这个监听是自己写的一个类,除了初始化方法,它还有销毁方法.用于关闭应用前释放资源.比如说数据库连接的关闭.
如:
<!-- 加载spring的配置文件 -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml,/WEB-
INF/jason-servlet.xml</param-value>
</context-param>
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
又如: --->自定义context-param,且自定义listener来获取这些信息
<context-param>
    <param-name>urlrewrite</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>cluster</param-name>
    <param-value>false</param-value>
</context-param>
<context-param>
    <param-name>servletmapping</param-name>
    <param-value>*.bbscs</param-value>
</context-param>
<context-param>
    <param-name>poststoragemode</param-name>
    <param-value>1</param-value>
</context-param>
<listener>
    <listener-class>com.laoer.bbscs.web.servlet.SysListener</listener-class>
</listener>
public class SysListener extends HttpServlet implements ServletContextListener {
private static final Log logger = LogFactory.getLog(SysListener.class);
public void contextDestroyed(ServletContextEvent sce) {
  //用于在容器关闭时,操作
}
//用于在容器开启时,操作
public void contextInitialized(ServletContextEvent sce) {
   String rootpath = sce.getServletContext().getRealPath("/");
   System.out.println("-------------rootPath:"+rootpath);
   if (rootpath != null) {
    rootpath = rootpath.replaceAll("\\\\", "/");
   } else {
    rootpath = "/";
   }
   if (!rootpath.endsWith("/")) {
    rootpath = rootpath + "/";
   }
   Constant.ROOTPATH = rootpath;
   logger.info("Application Run Path:" + rootpath);
   String urlrewrtie = sce.getServletContext().getInitParameter("urlrewrite");
   boolean burlrewrtie = false;
   if (urlrewrtie != null) {
    burlrewrtie = Boolean.parseBoolean(urlrewrtie);
   }
   Constant.USE_URL_REWRITE = burlrewrtie;
   logger.info("Use Urlrewrite:" + burlrewrtie);
   其它略之....
   }
}
   /*最终输出
   -------------rootPath:D:\tomcat_bbs\webapps\BBSCS_8_0_3\
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Application Run Path:D:/tomcat_bbs/webapps/BBSCS_8_0_3/
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Use Urlrewrite:true
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Use Cluster:false
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
SERVLET MAPPING:*.bbscs
   2009-06-09 21:51:46,573 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Post Storage Mode:1
   */
context-param和init-param区别
web.xml里面可以定义两种参数:
(1)application范围内的参数,存放在servletcontext中,在web.xml中配置如下:
<context-param>
           <param-name>context/param</param-name>
           <param-value>avalible during application</param-value>
</context-param>
(2)servlet范围内的参数,只能在servlet的init()方法中取得,在web.xml中配置如下:
<servlet>
    <servlet-name>MainServlet</servlet-name>
    <servlet-class>com.wes.controller.MainServlet</servlet-class>
    <init-param>
       <param-name>param1</param-name>
       <param-value>avalible in servlet init()</param-value>
    </init-param>
    <load-on-startup>0</load-on-startup>
</servlet>
在servlet中可以通过代码分别取用:
package com.wes.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class MainServlet extends HttpServlet ...{
    public MainServlet() ...{
        super();
     }
    public void init() throws ServletException ...{
         System.out.println("下面的两个参数param1是在servlet中存放的");
         System.out.println(this.getInitParameter("param1"));
         System.out.println("下面的参数是存放在servletcontext中的");
        System.out.println(getServletContext().getInitParameter("context/param"));
      }
}
第一种参数在servlet里面可以通过getServletContext().getInitParameter("context/param")得到
第二种参数只能在servlet的init()方法中通过this.getInitParameter("param1")取得.


文章来源自:http://www.cnblogs.com/hzj-/articles/1689836.html
posted @ 2013-05-27 11:45 Terry Zou 阅读(170) | 评论 (0)编辑 收藏
回调函数其实用起来比较简单,主要有三个部分
第一部分:定义一个接口用于回调;
如下所示:
public interface CallBackInterface {

     public void doSome();
     public void exectueMethod();
}

第二部分:在一个类里面把它当做参数并用到该参数
如下所示:

public class MethodB {

     public double getTime(CallBackInterface callBack){
          long start = System.currentTimeMillis();
          callBack.exectueMethod();
          long end = System.currentTimeMillis();
          System.out.println("cost time="+(end-start));
          return end-start;
     }
}

第三部分:在另外一个类里面调用到getTime方法并实现回调函数
如下所示:

public class MethodA {

     public static void main(String[] args) {
          MethodB b = new MethodB();
          double d = b.getTime(new CallBackInterface() {
         @Override
           public void exectueMethod() {
                // TODO Auto-generated method stub
                new MethodA().testMethod();
           }
   
           @Override
           public void doSome() {
                // TODO Auto-generated method stub
           }
          });
          System.out.println("d="+d);
     }
     public void testMethod(){
          for(int i=0;i<10000;i++)
           System.out.print("");
     }
}

输出结果:

cost time=31
d=31.0

理解“回调函数”

所谓回调,就是客户程序CLIENT调用服务程序SERVER中的某个函数SA,然后SERVER又在某个时候反过来调用CLIENT中的某个函数CB,对于CLIENT来说,这个CB便叫做回调函数。例如Win32下的窗口过程函数就是一个典型的回调函数。 
一般说来,CLIENT不会自己调用CB,CLIENT提供CB的目的就是让SERVER来调用它,而且是CLIENT不得不提供。由于SERVER并不知道CLIENT提供的CB叫甚名谁,所以SERVER会约定CB的接口规范(函数原型),然后由CLIENT提前通过SERVER的一个函数R告诉SERVER自己将要使用CB函数,这个过程称为回调函数的注册,R称为注册函数。Web SERVERerviCliente以及Java的RMI都用到回调机制,可以访问远程服务器程序。

下面举个通俗的例子:
某天,我打电话向你请教问题,当然是个难题,:),你一时想不出解决方法,我又不能拿着电话在那里傻等,于是我们约定:等你想出办法后打手机通知我,这样,我就挂掉电话办其它事情去了。过了XX分钟,我的手机响了,你兴高采烈的说问题已经搞定,应该如此这般处理。故事到此结束。这个例子说明了“异步+回调”的编程模式。其中,你后来打手机告诉我结果便是一个“回调”过程;我的手机号码必须在以前告诉你,这便是注册回调函数;我的手机号码应该有效并且手机能够接收到你的呼叫,这是回调函数必须符合接口规范。
通过上面个人感觉到回调函数更多的应用就是结合异步。比如:ajax中jServer通过组件和服务器的异步通信。

什么是回调函数

精妙比喻:回调函数还真有点像您随身带的BP机:告诉别人号码,在它有事情时Call您
回调用于层间协作,上层将本层函数安装在下层,这个函数就是回调,而下层在一定条件下触发回调,例如作为一个驱动,是一个底层,他在收到一个数据时,除了完成本层的处理工作外,还将进行回调,将这个数据交给上层应用层来做进一步处理,这在分层的数据通信中很普遍。
其实回调和API非常接近,他们的共性都是跨层调用的函数。但区别是API是低层提供给高层的调用,一般这个函数对高层都是已知的;而回调正好相反,他是高层提供给底层的调用,对于低层他是未知的,必须由高层进行安装,这个安装函数其实就是一个低层提供的API,安装后低层不知道这个回调的名字,但它通过一个函数指针来保存这个回调,在需要调用时,只需引用这个函数指针和相关的参数指针。

其实:回调就是该函数写在高层,低层通过一个函数指针保存这个函数,在某个事件的触发下,低层通过该函数指针调用高层那个函数。
【参考】
http://blog.csdn.net/sweetwxh/article/details/2067139
http://liutiemeng.blog.51cto.com/120361/18874
http://kidult.iteye.com/blog/148982

 

 

 




 

--

public static void main(String[] args) {
  MethodB b = new MethodB();
  double d = b.getTime(new CallBackInterface() {
   
   @Override
   public void exectueMethod() {
    // TODO Auto-generated method stub
    new MethodA().testMethod();
   }
   
   @Override
   public void doSome() {
    // TODO Auto-generated method stub
    
   }
  });
  System.out.println("d="+d);
 }
 public void testMethod(){
  for(int i=0;i<10000;i++)
   System.out.print("");
 }


 


posted @ 2013-05-27 11:13 Terry Zou 阅读(149) | 评论 (0)编辑 收藏
     摘要: --------------------------------------------------(一)androidpn-server服务器端启动的理解和分析-----------------------------------------------     在Androidpn的底层主要采用的两大框架mina和openfire两大框架,其中mi...  阅读全文
posted @ 2013-05-24 17:05 Terry Zou 阅读(5200) | 评论 (1)编辑 收藏
 这个方法的含义说明:
    这个方法的意思就是在jvm中增加一个关闭的钩子,当jvm关闭的时候,会执行系统中已经设置的所有通过方法addShutdownHook添加的钩子,当系统执行完这些钩子后,jvm才会关闭。所以这些钩子可以在jvm关闭的时候进行内存清理、对象销毁等操作。
测试类如下:
  1. public class RunTimeTest {
  2. /**
  3. * @param args
  4. */
  5. public static void main(String[] args) {
  6. Thread thread1 = new Thread() {
  7. public void run() {
  8. System.out.println("thread1...");
  9. }
  10. };
  11. Thread thread2 = new Thread() {
  12. public void run() {
  13. System.out.println("thread2...");
  14. }
  15. };
  16. Thread shutdownThread = new Thread() {
  17. public void run() {
  18. System.out.println("shutdownThread...");
  19. }
  20. };
  21. Runtime.getRuntime().addShutdownHook(shutdownThread);
  22. thread1.start();
  23. thread2.start();
  24. }
  25. }

打印结果为:
thread2...
thread1...
shutdownThread...

或者:
thread2...
thread1...
shutdownThread...

结论:
无论是先打印thread1还是thread2,shutdownThread 线程都是最后执行的(因为这个线程是在jvm执行关闭前才会执行)。

posted @ 2013-05-23 16:34 Terry Zou 阅读(231) | 评论 (0)编辑 收藏

Java程序来说,只要还有一个前台线程在运行,这个进程就不会结束,如果一个进程中只有后台线程在运行,这个进程就会结束。前台线程是相对后台线程而言的,前面所介绍的线程都是前台线程。那么什么样的线程是后台线程呢?如果某个线程对象在启动(调用start()方法)之前调用了setDaemon(true)方法,这个线程就变成了后台线程。下面来看一下进程中只有后台线程在运行的情况,如下所示:

范例:ThreadDaemon.java

01 public class ThreadDaemon

02 {

03 public static void main(String args[])

04 {

05 ThreadTest t = new ThreadTest() ;

06 Thread tt = new Thread(t) ;

07 tt.setDaemon(true) ; // 设置后台运行

08 tt.start();

09 }

10 }

11

12 class ThreadTest implements Runnable

13 {

14 public void run()

15 {

16 while(true)

17 {

18 System.out.println(Thread.currentThread().getName()+"is running.");

19 }

20 }

21 }

从上面的程序和运行结果(图9-4)上,可以看到:虽然创建了一个无限循环的线程,但因为它是后台线程,整个进程在主线程结束时就随之终止运行了。这验证了

进程中只有后台线程运行时,进程就会结束的说法。

posted @ 2013-05-23 09:09 Terry Zou 阅读(456) | 评论 (0)编辑 收藏

1、PendingIntent作用

根据字面意思就知道是延迟的intent,主要用来在某个事件完成后执行特定的Action。PendingIntent包含了Intent及Context,所以就算Intent所属程序结束,PendingIntent依然有效,可以在其他程序中使用。
常用在通知栏及短信发送系统中。

PendingIntent一般作为参数传给某个实例,在该实例完成某个操作后自动执行PendingIntent上的Action,也可以通过PendingIntent的send函数手动执行,并可以在send函数中设置OnFinished表示send成功后执行的动作。


2.举例(通知栏应用)
    界面A 定义一个notification    
    NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    int icon = R.drawable.notification;
    long when = System.currentTimeMillis()+2000;
    Notification n = new Notification(icon,"标题",when);
    n.defaults = Notification.DEFAULT_SOUND;
    n.flags |= Notification.FLAG_AUTO_CANCEL;
    Intent intent = new Intent(this,B.class);
    PendingIntent pi = new PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_CANCEL_CURRENT);
    n.setLatesEventInfo(this,"通知栏demo提醒title","通知栏demo提醒text",pi);
    nm.notify(0,n);

    B.界面Intent intent = getIntent();
  String title = intent.getStringExtra("title");

    效果,当A界面显示,生成一个按钮,点击该按钮生成如上所示的通知栏,点击通知栏,则显示B界面,参数title为所显示的值。

3、Intent和PendingIntent的区别

a. Intent是立即使用的,而PendingIntent可以等到事件发生后触发,PendingIntent可以cancel
b. Intent在程序结束后即终止,而PendingIntent在程序结束后依然有效
c. PendingIntent自带Context,而Intent需要在某个Context内运行
d. Intent在原task中运行,PendingIntent在新的task中运行


posted @ 2013-05-22 15:34 Terry Zou 阅读(240) | 评论 (0)编辑 收藏

PhoneStateListener
1.对特定的电话状态的监听,包括服务的状态、信号强度、消息等待指示(语音信箱)、通话转移、呼叫状态、设备单元位置、数据连接状态、数据流量方向。一些电话信息受权限保护,应用程序不会收到受保护的信息的更新,除非在manifest文件中有适当的权限声明。凡申请许可,有适当的LISTEN_标志。

2.对监听的话做处理
Handler mHandler = new Handler() {
   public void handleMessage(Message msg) {
       switch (msg.what) {
           case LISTEN_SERVICE_STATE:/*Listen for changes to the network service state (cellular).对网络服务状态监听*/
              PhoneStateListener.this.onServiceStateChanged((ServiceState)msg.obj);
              break;
           case LISTEN_SIGNAL_STRENGTH:/*Listen for changes to the network signal strength (cellular).对网络信号强度变化监听*/
              PhoneStateListener.this.onSignalStrengthChanged(msg.arg1);
              break;
           case LISTEN_MESSAGE_WAITING_INDICATOR:/*Listen for changes to the message-waiting indicator.对消息等待指示的变化监听*/
              PhoneStateListener.this.onMessageWaitingIndicatorChanged(msg.arg1 != 0);
              break;
           case LISTEN_CALL_FORWARDING_INDICATOR:/*Listen for changes to the call-forwarding indicator.对通话转移指示的变化监听*/
              PhoneStateListener.this.onCallForwardingIndicatorChanged(msg.arg1 != 0);
              break;
           case LISTEN_CELL_LOCATION:/*Listen for changes to the device's cell location. Note that this will result in frequent callbacks to the listener.对设备单元位置的变化监听,这会导致频繁的监听回调。*/
              PhoneStateListener.this.onCellLocationChanged((CellLocation)msg.obj);
              break;
           case LISTEN_CALL_STATE:/*Listen for changes to the device call state.对设备呼叫状态的变化监听。*/
              PhoneStateListener.this.onCallStateChanged(msg.arg1, (String)msg.obj);
              break;
           case LISTEN_DATA_CONNECTION_STATE:/*Listen for changes to the data connection state (cellular).对数据连接状态的变化监听。*/
              PhoneStateListener.this.onDataConnectionStateChanged(msg.arg1, msg.arg2);
              PhoneStateListener.this.onDataConnectionStateChanged(msg.arg1);
              break;
           case LISTEN_DATA_ACTIVITY:/*Listen for changes to the direction of data traffic on the data connection (cellular).对数据流量移动方向的变化监听*/
            PhoneStateListener.this.onDataActivity(msg.arg1);
              break;
           case LISTEN_SIGNAL_STRENGTHS:/*Listen for changes to the network signal strengths (cellular).对网络信号强度的变化监听*/
              PhoneStateListener.this.onSignalStrengthsChanged((SignalStrength)msg.obj);
              break;
      }
   }
};

3.监听变化后发送消息
IPhoneStateListener callback = new IPhoneStateListener.Stub() {
    public void onServiceStateChanged(ServiceState serviceState) {
        Message.obtain(mHandler, LISTEN_SERVICE_STATE, 0, 0, serviceState).sendToTarget();
    }
    public void onSignalStrengthChanged(int asu) {
        Message.obtain(mHandler, LISTEN_SIGNAL_STRENGTH, asu, 0, null).sendToTarget();
    }
    public void onMessageWaitingIndicatorChanged(boolean mwi) {
        Message.obtain(mHandler, LISTEN_MESSAGE_WAITING_INDICATOR, mwi ? 1 : 0, 0, null)
                .sendToTarget();
    }
    public void onCallForwardingIndicatorChanged(boolean cfi) {
        Message.obtain(mHandler, LISTEN_CALL_FORWARDING_INDICATOR, cfi ? 1 : 0, 0, null)
                .sendToTarget();
    }
    public void onCellLocationChanged(Bundle bundle) {
        CellLocation location = CellLocation.newFromBundle(bundle);
        Message.obtain(mHandler, LISTEN_CELL_LOCATION, 0, 0, location).sendToTarget();
    }
    public void onCallStateChanged(int state, String incomingNumber) {
        Message.obtain(mHandler, LISTEN_CALL_STATE, state, 0, incomingNumber).sendToTarget();
    }
    public void onDataConnectionStateChanged(int state, int networkType) {
        Message.obtain(mHandler, LISTEN_DATA_CONNECTION_STATE, state, networkType, null).
                sendToTarget();
    }
    public void onDataActivity(int direction) {
        Message.obtain(mHandler, LISTEN_DATA_ACTIVITY, direction, 0, null).sendToTarget();
    }
    public void onSignalStrengthsChanged(SignalStrength signalStrength) {
        Message.obtain(mHandler, LISTEN_SIGNAL_STRENGTHS, 0, 0, signalStrength).sendToTarget();
    }
};

posted @ 2013-05-18 09:38 Terry Zou 阅读(347) | 评论 (0)编辑 收藏
仅列出标题
共8页: 上一页 1 2 3 4 5 6 7 8 下一页 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

常用链接

留言簿(2)

随笔分类

随笔档案

文章分类

文章档案

相册

收藏夹

Java

搜索

  •  

最新随笔

最新评论

阅读排行榜

评论排行榜