Apache Shiro—–Java权限安全框架

先记录,后学习!

学习链接:http://www.9iu.org/2013/12/10/springrain1-shiro.html

http://www.ibm.com/developerworks/cn/java/j-lo-shiro/

一、什么是Shiro
Apache Shiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能:

  • 认证 – 用户身份识别,常被称为用户“登录”;
  • 授权 – 访问控制;
  • 密码加密 – 保护或隐藏数据防止被偷窥;
  • 会话管理 – 每用户相关的时间敏感的状态。

对于任何一个应用程序,Shiro都可以提供全面的安全管理服务。并且相对于其他安全框架,Shiro要简单的多。

二、Shiro的架构介绍
首先,来了解一下Shiro的三个核心组件:Subject, SecurityManager 和 Realms. 如下图:

Subject:即“当前操作用户”。但是,在Shiro中,Subject这一概念并不仅仅指人,也可以是第三方进程、后台帐户(Daemon Account)或其他类似事物。它仅仅意味着“当前跟软件交互的东西”。但考虑到大多数目的和用途,你可以把它认为是Shiro的“用户”概念。
Subject代表了当前用户的安全操作,SecurityManager则管理所有用户的安全操作。

SecurityManager:它是Shiro框架的核心,典型的Facade模式,Shiro通过SecurityManager来管理内部组件实例,并通过它来提供安全管理的各种服务。

Realm: Realm充当了Shiro与应用安全数据间的“桥梁”或者“连接器”。也就是说,当对用户执行认证(登录)和授权(访问控制)验证时,Shiro会从应用配置的Realm中查找用户及其权限信息。
从这个意义上讲,Realm实质上是一个安全相关的DAO:它封装了数据源的连接细节,并在需要时将相关数据提供给Shiro。当配置Shiro时,你必须至少指定一个Realm,用于认证和(或)授权。配置多个Realm是可以的,但是至少需要一个。
Shiro内置了可以连接大量安全数据源(又名目录)的Realm,如LDAP、关系数据库(JDBC)、类似INI的文本配置资源以及属性文件等。如果缺省的Realm不能满足需求,你还可以插入代表自定义数据源的自己的Realm实现。

Shiro完整架构图:


除前文所讲Subject、SecurityManager 、Realm三个核心组件外,Shiro主要组件还包括:
Authenticator :认证就是核实用户身份的过程。这个过程的常见例子是大家都熟悉的“用户/密码”组合。多数用户在登录软件系统时,通常提供自己的用户名(当事人)和支持他们的密码(证书)。如果存储在系统中的密码(或密码表示)与用户提供的匹配,他们就被认为通过认证。
Authorizer :授权实质上就是访问控制 – 控制用户能够访问应用中的哪些内容,比如资源、Web页面等等。
SessionManager :在安全框架领域,Apache Shiro提供了一些独特的东西:可在任何应用或架构层一致地使用Session API。即,Shiro为任何应用提供了一个会话编程范式 – 从小型后台独立应用到大型集群Web应用。这意味着,那些希望使用会话的应用开发者,不必被迫使用Servlet或EJB容器了。或者,如果正在使用这些容器,开发者现在也可以选择使用在任何层统一一致的会话API,取代Servlet或EJB机制。
CacheManager :对Shiro的其他组件提供缓存支持。

原文链接:http://kdboy.iteye.com/blog/1154644

Shiro与Spring集成:

Shiro的组件都是JavaBean/POJO式的组件,所以非常容易使用Spring进行组件管理,可以非常方便的从ini配置迁移到Spring进行管理,且支持JavaSE应用及Web应用的集成。

 

在示例之前,需要导入shiro-spring及spring-context依赖,具体请参考pom.xml。

spring-beans.xml配置文件提供了基础组件如DataSource、DAO、Service组件的配置。

 

JavaSE应用

 

spring-shiro.xml提供了普通JavaSE独立应用的Spring配置:

Java代码

  1. <!–?缓存管理器?使用Ehcache实现?–>
  2. <bean?id=”cacheManager”?class=”org.apache.shiro.cache.ehcache.EhCacheManager”>
  3. ????<property?name=”cacheManagerConfigFile”?value=”classpath:ehcache.xml”/>
  4. </bean>
  5. <!–?凭证匹配器?–>
  6. <bean?id=”credentialsMatcher”?class=”
  7. com.github.zhangkaitao.shiro.chapter12.credentials.RetryLimitHashedCredentialsMatcher”>
  8. ????<constructor-arg?ref=”cacheManager”/>
  9. ????<property?name=”hashAlgorithmName”?value=”md5″/>
  10. ????<property?name=”hashIterations”?value=”2″/>
  11. ????<property?name=”storedCredentialsHexEncoded”?value=”true”/>
  12. </bean>
  13. <!–?Realm实现?–>
  14. <bean?id=”userRealm”?class=”com.github.zhangkaitao.shiro.chapter12.realm.UserRealm”>
  15. ????<property?name=”userService”?ref=”userService”/>
  16. ????<property?name=”credentialsMatcher”?ref=”credentialsMatcher”/>
  17. ????<property?name=”cachingEnabled”?value=”true”/>
  18. ????<property?name=”authenticationCachingEnabled”?value=”true”/>
  19. ????<property?name=”authenticationCacheName”?value=”authenticationCache”/>
  20. ????<property?name=”authorizationCachingEnabled”?value=”true”/>
  21. ????<property?name=”authorizationCacheName”?value=”authorizationCache”/>
  22. </bean>
  23. <!–?会话ID生成器?–>
  24. <bean?id=”sessionIdGenerator”
  25. class=”org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator”/>
  26. <!–?会话DAO?–>
  27. <bean?id=”sessionDAO”
  28. class=”org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO”>
  29. ????<property?name=”activeSessionsCacheName”?value=”shiro-activeSessionCache”/>
  30. ????<property?name=”sessionIdGenerator”?ref=”sessionIdGenerator”/>
  31. </bean>
  32. <!–?会话验证调度器?–>
  33. <bean?id=”sessionValidationScheduler”
  34. class=”org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler”>
  35. ????<property?name=”sessionValidationInterval”?value=”1800000″/>
  36. ????<property?name=”sessionManager”?ref=”sessionManager”/>
  37. </bean>
  38. <!–?会话管理器?–>
  39. <bean?id=”sessionManager”?class=”org.apache.shiro.session.mgt.DefaultSessionManager”>
  40. ????<property?name=”globalSessionTimeout”?value=”1800000″/>
  41. ????<property?name=”deleteInvalidSessions”?value=”true”/>
  42. ????<property?name=”sessionValidationSchedulerEnabled”?value=”true”/>
  43. ???<property?name=”sessionValidationScheduler”?ref=”sessionValidationScheduler”/>
  44. ????<property?name=”sessionDAO”?ref=”sessionDAO”/>
  45. </bean>
  46. <!–?安全管理器?–>
  47. <bean?id=”securityManager”?class=”org.apache.shiro.mgt.DefaultSecurityManager”>
  48. ????<property?name=”realms”>
  49. ????????<list><ref?bean=”userRealm”/></list>
  50. ????</property>
  51. ????<property?name=”sessionManager”?ref=”sessionManager”/>
  52. ????<property?name=”cacheManager”?ref=”cacheManager”/>
  53. </bean>
  54. <!–?相当于调用SecurityUtils.setSecurityManager(securityManager)?–>
  55. <bean?class=”org.springframework.beans.factory.config.MethodInvokingFactoryBean”>
  56. <property?name=”staticMethod”
  57. value=”org.apache.shiro.SecurityUtils.setSecurityManager”/>
  58. ????<property?name=”arguments”?ref=”securityManager”/>
  59. </bean>
  60. <!–?Shiro生命周期处理器–>
  61. <bean?id=”lifecycleBeanPostProcessor”
  62. class=”org.apache.shiro.spring.LifecycleBeanPostProcessor”/>

可以看出,只要把之前的ini配置翻译为此处的spring xml配置方式即可,无须多解释。LifecycleBeanPostProcessor用于在实现了Initializable接口的Shiro bean初始化时调用Initializable接口回调,在实现了Destroyable接口的Shiro bean销毁时调用?Destroyable接口回调。如UserRealm就实现了Initializable,而DefaultSecurityManager实现了Destroyable。具体可以查看它们的继承关系。

 

测试用例请参考com.github.zhangkaitao.shiro.chapter12.ShiroTest。

 

Web应用

Web应用和普通JavaSE应用的某些配置是类似的,此处只提供一些不一样的配置,详细配置可以参考spring-shiro-web.xml。

Java代码

  1. <!–?会话Cookie模板?–>
  2. <bean?id=”sessionIdCookie”?class=”org.apache.shiro.web.servlet.SimpleCookie”>
  3. ????<constructor-arg?value=”sid”/>
  4. ????<property?name=”httpOnly”?value=”true”/>
  5. ????<property?name=”maxAge”?value=”180000″/>
  6. </bean>
  7. <!–?会话管理器?–>
  8. <bean?id=”sessionManager”
  9. class=”org.apache.shiro.web.session.mgt.DefaultWebSessionManager”>
  10. ????<property?name=”globalSessionTimeout”?value=”1800000″/>
  11. ????<property?name=”deleteInvalidSessions”?value=”true”/>
  12. ????<property?name=”sessionValidationSchedulerEnabled”?value=”true”/>
  13. ????<property?name=”sessionValidationScheduler”?ref=”sessionValidationScheduler”/>
  14. ????<property?name=”sessionDAO”?ref=”sessionDAO”/>
  15. ????<property?name=”sessionIdCookieEnabled”?value=”true”/>
  16. ????<property?name=”sessionIdCookie”?ref=”sessionIdCookie”/>
  17. </bean>
  18. <!–?安全管理器?–>
  19. <bean?id=”securityManager”?class=”org.apache.shiro.web.mgt.DefaultWebSecurityManager”>
  20. <property?name=”realm”?ref=”userRealm”/>
  21. ????<property?name=”sessionManager”?ref=”sessionManager”/>
  22. ????<property?name=”cacheManager”?ref=”cacheManager”/>
  23. </bean>

1、sessionIdCookie是用于生产Session ID Cookie的模板;

2、会话管理器使用用于web环境的DefaultWebSessionManager;

3、安全管理器使用用于web环境的DefaultWebSecurityManager。

 

Java代码

  1. <!–?基于Form表单的身份验证过滤器?–>
  2. <bean?id=”formAuthenticationFilter”
  3. class=”org.apache.shiro.web.filter.authc.FormAuthenticationFilter”>
  4. ????<property?name=”usernameParam”?value=”username”/>
  5. ????<property?name=”passwordParam”?value=”password”/>
  6. ????<property?name=”loginUrl”?value=”/login.jsp”/>
  7. </bean>
  8. <!–?Shiro的Web过滤器?–>
  9. <bean?id=”shiroFilter”?class=”org.apache.shiro.spring.web.ShiroFilterFactoryBean”>
  10. ????<property?name=”securityManager”?ref=”securityManager”/>
  11. ????<property?name=”loginUrl”?value=”/login.jsp”/>
  12. ????<property?name=”unauthorizedUrl”?value=”/unauthorized.jsp”/>
  13. ????<property?name=”filters”>
  14. ????????<util:map>
  15. ????????????<entry?key=”authc”?value-ref=”formAuthenticationFilter”/>
  16. ????????</util:map>
  17. ????</property>
  18. ????<property?name=”filterChainDefinitions”>
  19. ????????<value>
  20. ????????????/index.jsp?=?anon
  21. ????????????/unauthorized.jsp?=?anon
  22. ????????????/login.jsp?=?authc
  23. ????????????/logout?=?logout
  24. ????????????/**?=?user
  25. ????????</value>
  26. ????</property>
  27. </bean>

1、formAuthenticationFilter为基于Form表单的身份验证过滤器;此处可以再添加自己的Filter bean定义;

2、shiroFilter:此处使用ShiroFilterFactoryBean来创建ShiroFilter过滤器;filters属性用于定义自己的过滤器,即ini配置中的[filters]部分;filterChainDefinitions用于声明url和filter的关系,即ini配置中的[urls]部分。

 

接着需要在web.xml中进行如下配置:

Java代码

  1. <context-param>
  2. ????<param-name>contextConfigLocation</param-name>
  3. ????<param-value>
  4. ????????classpath:spring-beans.xml,
  5. ????????classpath:spring-shiro-web.xml
  6. ????</param-value>
  7. </context-param>
  8. <listener>
  9. ???<listener-class>
  10. org.springframework.web.context.ContextLoaderListener
  11. </listener-class>
  12. </listener>

通过ContextLoaderListener加载contextConfigLocation指定的Spring配置文件。

 

Java代码

  1. <filter>
  2. ????<filter-name>shiroFilter</filter-name>
  3. ????<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
  4. ????<init-param>
  5. ????????<param-name>targetFilterLifecycle</param-name>
  6. ????????<param-value>true</param-value>
  7. ????</init-param>
  8. </filter>
  9. <filter-mapping>
  10. ????<filter-name>shiroFilter</filter-name>
  11. ????<url-pattern>/*</url-pattern>
  12. </filter-mapping>

DelegatingFilterProxy会自动到Spring容器中查找名字为shiroFilter的bean并把filter请求交给它处理。

 

其他配置请参考源代码。

 

Shiro权限注解

Shiro提供了相应的注解用于权限控制,如果使用这些注解就需要使用AOP的功能来进行判断,如Spring AOP;Shiro提供了Spring AOP集成用于权限注解的解析和验证。

为了测试,此处使用了Spring MVC来测试Shiro注解,当然Shiro注解不仅仅可以在web环境使用,在独立的JavaSE中也是可以用的,此处只是以web为例了。

 

在spring-mvc.xml配置文件添加Shiro Spring AOP权限注解的支持:

Java代码

  1. <aop:config?proxy-target-class=”true”></aop:config>
  2. <bean?class=”
  3. org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor”>
  4. ????<property?name=”securityManager”?ref=”securityManager”/>
  5. </bean>

如上配置用于开启Shiro Spring AOP权限注解的支持;<aop:config proxy-target-class=”true”>表示代理类。

 

接着就可以在相应的控制器(AnnotationController)中使用如下方式进行注解:

Java代码

  1. @RequiresRoles(“admin”)
  2. @RequestMapping(“/hello2”)
  3. public?String?hello2()?{
  4. ????return?”success”;
  5. }

访问hello2方法的前提是当前用户有admin角色。

 

当验证失败,其会抛出UnauthorizedException异常,此时可以使用Spring的ExceptionHandler(DefaultExceptionHandler)来进行拦截处理:

Java代码

  1. @ExceptionHandler({UnauthorizedException.class})
  2. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  3. public?ModelAndView?processUnauthenticatedException(NativeWebRequest?request,?UnauthorizedException?e)?{
  4. ????ModelAndView?mv?=?new?ModelAndView();
  5. ????mv.addObject(“exception”,?e);
  6. ????mv.setViewName(“unauthorized”);
  7. ????return?mv;
  8. }

如果集成Struts2,需要注意《Shiro+Struts2+Spring3?加上@RequiresPermissions?后@Autowired失效》问题:

http://jinnianshilongnian.iteye.com/blog/1850425

 

权限注解

Java代码

  1. @RequiresAuthentication

表示当前Subject已经通过login进行了身份验证;即Subject. isAuthenticated()返回true。

 

Java代码

  1. @RequiresUser

表示当前Subject已经身份验证或者通过记住我登录的。

 

Java代码

  1. @RequiresGuest

表示当前Subject没有身份验证或通过记住我登录过,即是游客身份。

 

Java代码

  1. @RequiresRoles(value={“admin”,?“user”},?logical=?Logical.AND)

表示当前Subject需要角色admin和user。

 

Java代码

  1. @RequiresPermissions?(value={“user:a”,?“user:b”},?logical=?Logical.OR)

表示当前Subject需要权限user:a或user:b。

 

 

链接:http://jinnianshilongnian.iteye.com/blog/2029717

android入门之文件系统操作

(一)获取总根
File[] fileList=File.listRoots();
//返回fileList.length为1
//fileList.getAbsolutePath()为”/”
//这就是系统的总根
File[] fileList=File.listRoots(); //返回fileList.length为1 //fileList.getAbsolutePath()为”/” //这就是系统的总根
(二)打开总根目录
File file=new File(“/”);
File[] fileList=file.listFiles();

//获取的目录中除了”/sdcard”和”/system”还有”/data”、”/cache”、”/dev”等
//Android的根目录并不像Symbian系统那样分为C盘、D盘、E盘等
//Android是基于Linux的,只有目录,无所谓盘符
File file=new File(“/”); File[] fileList=file.listFiles();

//获取的目录中除了”/sdcard”和”/system”还有”/data”、”/cache”、”/dev”等 //Android的根目录并不像Symbian系统那样分为C盘、D盘、E盘等 //Android是基于Linux的,只有目录,无所谓盘符
(三)获取系统存储根目录
File file=Environment.getRootDirectory();//File file=new File(“/system”);
File[] fileList=file.listFiles();
//这里说的系统仅仅指”/system”
//不包括外部存储的手机存储的范围远远大于所谓的系统存储
File file=Environment.getRootDirectory();

//File file=new File(“/system”); File[] fileList=file.listFiles();

//这里说的系统仅仅指”/system”

//不包括外部存储的手机存储的范围远远大于所谓的系统存储
(四)获取SD卡存储根目录
File file=Environment.getExternalStorageDirectory();//File file=new File(“/sdcard”);
File[] fileList=file.listFiles();
//要获取SD卡首先要确认SD卡是否装载
boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
//如果true,则已装载
//如果false,则未装载
File file=Environment.getExternalStorageDirectory();//File file=new File(“/sdcard”); File[] fileList=file.listFiles(); //要获取SD卡首先要确认SD卡是否装载 boolean is=Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED); //如果true,则已装载 //如果false,则未装载
(五)获取data根目录
File file=Environment.getDataDirectory();//File file=new File(“/data”);
File[] fileList=file.listFiles();
//由于data文件夹是android里一个非常重要的文件夹,所以一般权限是无法获取到文件的,即fileList.length返回为0
File file=Environment.getDataDirectory();//File file=new File(“/data”); File[] fileList=file.listFiles(); //由于data文件夹是android里一个非常重要的文件夹,所以一般权限是无法获取到文件的,即fileList.length返回为0
(六)获取私有文件路径
Context context=this;//首先,在Activity里获取context
File file=context.getFilesDir();
String path=file.getAbsolutePath();
//此处返回的路劲为/data/data/包/files,其中的包就是我们建立的主Activity所在的包
//我们可以看到这个路径也是在data文件夹下
//程序本身是可以对自己的私有文件进行操作
//程序中很多私有的数据会写入到私有文件路径下,这也是android为什么对data数据做保护的原因之一
Context context=this;//首先,在Activity里获取context File file=context.getFilesDir(); String path=file.getAbsolutePath(); //此处返回的路劲为/data/data/包/files,其中的包就是我们建立的主Activity所在的包 //我们可以看到这个路径也是在data文件夹下 //程序本身是可以对自己的私有文件进行操作 //程序中很多私有的数据会写入到私有文件路径下,这也是android为什么对data数据做保护的原因之一
(七)获取文件(夹)绝对路径、相对路劲、文件(夹)名、父目录
File file=……
String relativePath=file.getPath();//相对路径
String absolutePath=file.getAbsolutePath();//绝对路径
String fileName=file.getName();//文件(夹)名
String parentPath=file.getParent();//父目录
File file=…… String relativePath=file.getPath();//相对路径 String absolutePath=file.getAbsolutePath();//绝对路径 String fileName=file.getName();//文件(夹)名 String parentPath=file.getParent();//父目录
(八)列出文件夹下的所有文件和文件夹
File file=……
File[] fileList=file.listFiles();
File file=…… File[] fileList=file.listFiles();
(九)判断是文件还是文件夹
File file=……
boolean is=file.isDirectory();//true-是,false-否
File file=…… boolean is=file.isDirectory();//true-是,false
(十)判断文件(夹)是否存在
File file=……
boolean is=file.exists();//true-是,false-否
File file=…… boolean is=file.exists();//true-是,false-否
(十一)新建文件(夹)
File file=……
oolean is=file.isDirectory();//判断是否为文件夹
/*方法1*/
if(is){
String path=file.getAbsolutePath();
String name=”ABC”;//你要新建的文件夹名或者文件名
String pathx=path+name;
File filex=new File(pathx);
boolean is=filex.exists();//判断文件(夹)是否存在
if(!is){
filex.mkdir();//创建文件夹
//filex.createNewFile();//创建文件
}
/*方法2*/
if(is){
String path=file.getAbsolutePath();
String name=”test.txt”;//你要新建的文件夹名或者文件名
File filex=new File(path,name);//方法1和方法2的区别在于此
boolean is=filex.exists();//判断文件(夹)是否存在
if(!is){
filex.mkdir();//创建文件夹
//filex.createNewFile();//创建文件
}
File file=…… oolean is=file.isDirectory();//判断是否为文件夹 /*方法1*/ if(is){ String path=file.getAbsolutePath(); String name=”ABC”;//你要新建的文件夹名或者文件名 String pathx=path+name; File filex=new File(pathx); boolean is=filex.exists();//判断文件(夹)是否存在 if(!is){ filex.mkdir();//创建文件夹 //filex.createNewFile();//创建文件 } /*方法2*/ if(is){ String path=file.getAbsolutePath(); String name=”test.txt”;//你要新建的文件夹名或者文件名 File filex=new File(path,name);//方法1和方法2的区别在于此 boolean is=filex.exists();//判断文件(夹)是否存在 if(!is){ filex.mkdir();//创建文件夹 //filex.createNewFile();//创建文件 }
(十二)重命名文件(夹)
File file=……
String parentPath=file.getParent();
String newName=”name”;//重命名后的文件或者文件夹名
File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName)
file.renameTo(filex);
File file=…… String parentPath=file.getParent(); String newName=”name”;//重命名后的文件或者文件夹名 File filex=new File(parentPath,newName);//File filex=new File(parentPaht+newName) file.renameTo(filex)
(十三)删除文件(夹)
File file=……
file.delete();//立即删除
//file.deleteOnExit();//程序退出后删除,只有正常退出才会删除

(十四)获得所有可存储的路径,可能包括手机内置的SD卡和外置的SD卡

(不同手机Environment.getExternalStorageDirectory()获得路径不一样)

String starageStr = “”;

StorageManager sm = (StorageManager)context.getSystemService(Context.STORAGE_SERVICE);
try {
String[] paths = (String[]) sm.getClass().getMethod(“getVolumePaths”, null).invoke(sm, null);
for (int i = paths.length – 1; i > -1; i–) {
String status = (String) sm.getClass()
.getMethod(“getVolumeState”, String.class).invoke(sm, paths[i]);
if (status.equals(android.os.Environment.MEDIA_MOUNTED)) {
// SDCARD_PATH = paths[i];
// break;
starageStr+=paths[i];
}
}
} catch (Exception e) {}

(十五)下载缓存目录

File downloadCacheDir = Environment.getDownloadCacheDirectory();

(十六)检查设备的外存是否是内存模拟的

boolean isEmu = Environment.isExternalStorageEmulated();

(十七)检查外存是否是可拆卸的

boolean canRemoved = Environment.isExternalStorageRemovable();

后台线程如何正确发送消息(来自内网)

作者:xuding 转过来作为记录。

由于历史原因,我们有的APP依然使用webservice进行网络请求,我们为此封装了WebserviceUtils工具类,这个类具有明显的工具类特点——不与界面业务有任何耦合,这本应是个不错的设计。
然而我们长大后确发现,正因为不与界面耦合,WebserviceUtils在请求操作出错时,无法向界面传递消息,起初我们纠结万分,痛苦之中在研究了android Looper类的源码,于是我们自以为掌握了android消息队列的原理,参考:
http://www.cnblogs.com/codingmyworld/archive/2011/09/14/2174255.html
于是有了如下代码:

01.try {

02. // 网络请求

03.} catch (Exception e) {

04. Log.e(TAG, “请求超时”, e);

05. Activity activity = ActivityStackManager.getCurrentActivity();

06. Looper.prepare();

07. SysUtils.closeHint();

08. Toast.makeText(activity, “网络通讯异常,请检查网络…”, Toast.LENGTH_LONG).show();

09. Looper.loop();

10.}
复制代码这样书写终于可以弹出提示了,然而悲剧的是,弹出提示紧接着,界面就失去响应(ANR),曾记否,那一年的冬天,大约也是这个季节,当时客户现场不断传来APP停止响应的呼吼,出错现象如同雪花在面前纷纷扬扬,而我们居然一片都抓不住啊
说正题,此处的问题很经典,需要从后台线程向界面上展示消息,Android展示消息只能在主线程里操作。Android中每个线程都有handler对象,消息框(Toast)、对话框等都是通过主线程的handler操作消息对列来做的。
上述代码中的Looper.prepare()、Looper.loop()是参考Handler.java源码来做的,那么为什么会ANR呢?
关键就是这里的loop(),和其他系统一样,android的消息队列也是通过死循环实现的:

01.for (;;) {

02. Message msg = queue.next(); // might block

03. if (msg == null) {

04. // No message indicates that the message queue is quitting.

05. return;

06. }

07. msg.target.dispatchMessage(msg);

08. // 。。。。。

09. msg.recycle();

10.}
复制代码低版本sdk中是while(){…),都一样,在后台线程loop()之后,因为这个死循环,该线程就一直处于阻塞状态了,于是这里的消息也就成了APP临终的遗言,紧接着ANR失去响应,然后就没有然后了。。。因为是死循环导致出错,所以APP捕获不到uncaughtException,也就无法输出错误日志了,于是更加让人不明所以,加大了排查错误的难度。
那么问题来了,后台线程究竟有没有办法向前台发消息呢?当然有,其实我们有了上述的知识,离胜利已经很近了:

01.new Handler(Looper.getMainLooper()).post(new Runnable() {

02. @Override

03. public void run() {

04. SysUtils.closeHint();

05. Toast.makeText(activity, “网络通讯异常,请检查网络…”, Toast.LENGTH_LONG).show();

06. }

07.});
复制代码非常优雅的通过Looper.getMainLooper()得到主线程handler,然后post!
非常简单吧!这个故事告诉我们一个道理,凡事一要求甚解,知其然还要知其所以然。我们有时候闭门造车容易将自己蒙蔽,吾尝终日而思,不如须臾之所学也。当我们脚踏实地,蓦然回首,就会发现,原来希望一直都在我们身边,只是我们被雪花迷失了方向。。。
万幸的是,这样的错误,我们以后的APP开发中很难再出现了,我们使用的annotations框架可以很优雅的处理各种对话框,从此Looper.loop()、AnsyncTask、Handler都成为了过往的种种。。。
其实Annotations处理主线程事件,也是通过上面的new Handler(Looper.getMainLooper()).post(…)来做的,欲知Annotations如何,且听下回分解~