binder的异常处理

ぐ巨炮叔叔 提交于 2020-02-05 19:06:36

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!