binder的异常处理详解手机开发

binder的异常处理真的很捉急,一开始我以为RemoteException可以跨进程交互,之后看了资料和源码才知道,RemoteException根本就支持跨进程传递

在Parcel.java源码注明了可以传递的几种异常

public final void writeException(Exception e) {
    
    int code = 0; 
    if (e instanceof Parcelable 
            && (e.getClass().getClassLoader() == Parcelable.class.getClassLoader())) {
    
        // We only send Parcelable exceptions that are in the 
        // BootClassLoader to ensure that the receiver can unpack them 
        code = EX_PARCELABLE; 
    } else if (e instanceof SecurityException) {
    
        code = EX_SECURITY; 
    } else if (e instanceof BadParcelableException) {
    
        code = EX_BAD_PARCELABLE; 
    } else if (e instanceof IllegalArgumentException) {
    
        code = EX_ILLEGAL_ARGUMENT; 
    } else if (e instanceof NullPointerException) {
    
        code = EX_NULL_POINTER; 
    } else if (e instanceof IllegalStateException) {
    
        code = EX_ILLEGAL_STATE; 
    } else if (e instanceof NetworkOnMainThreadException) {
    
        code = EX_NETWORK_MAIN_THREAD; 
    } else if (e instanceof UnsupportedOperationException) {
    
        code = EX_UNSUPPORTED_OPERATION; 
    } else if (e instanceof ServiceSpecificException) {
    
        code = EX_SERVICE_SPECIFIC; 
    } 
    writeInt(code); 
    StrictMode.clearGatheredViolations(); 
    if (code == 0) {
    
        if (e instanceof RuntimeException) {
    
            throw (RuntimeException) e; 
        } 
        throw new RuntimeException(e); 
    } 
    writeString(e.getMessage()); 
} 

所以支持的传递的异常有:

  • SecurityException
  • BadParcelableException
  • IllegalArgumentException
  • NullPointerException
  • IllegalStateException
  • NetworkOnMainThreadException
  • UnsupportedOperationException
  • ServiceSpecificException
  • BootClassLoader 加载的Parcelable以及子类

那我们创建一个子类继承了Parcelable是否可以传递,实际上是不行的,因为该子类不是由BootClassLoader加载的,而一般android的类都是由pathClassLoader或者dexClassLoader加载,DexClassLoader能够加载未安装的jar/apk/dex,PathClassLoader只能加载系统中已经安装过的apk

原创文章,作者:奋斗,如若转载,请注明出处:https://blog.ytso.com/6239.html

(0)
上一篇 2021年7月17日
下一篇 2021年7月17日

相关推荐

发表回复

登录后才能评论