Android检查某so是否存在

/**
 * Created by xievxin on 2018/9/26
 */
public class SoChecker {

    private static final String TAG = "SoChecker";

    public void checkSoExist(final Context context, String soName) {
        if ((context.getApplicationInfo().flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0) {
            // debug模式才检查
            return;
        }

        boolean isSoExist;

        try {
            // 先从安装目录检查
            File file = new File(context.getApplicationInfo().nativeLibraryDir, soName);
            if (!(isSoExist = file.exists())) {
                // SDK可能做为插件加载的,安装目录下没有,从DexClassLoader加载的so路径去找
                isSoExist = checkSoByDynamic(soName);
            }

            if (!isSoExist) {
                final String errMsg = soName + " not found in path: " + file.getAbsolutePath();

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        Toast.makeText(context, errMsg, Toast.LENGTH_LONG).show();
                    }
                });
                Log.e(TAG, errMsg);
            }
        } catch (Throwable e) {
            // #debug
            e.printStackTrace();
        }
    }

    private boolean checkSoByDynamic(String soName) {
        try {
            ClassLoader dexClassLoader = getClass().getClassLoader();
            Field field = dexClassLoader.getClass().getSuperclass().getDeclaredField("pathList");
            field.setAccessible(true);
            Object pathListObj = field.get(dexClassLoader);

            Class dplCls = Class.forName("dalvik.system.DexPathList");
            Field field1 = dplCls.getDeclaredField("nativeLibraryDirectories");
            field1.setAccessible(true);
            Object nativeLibraryObj = field1.get(pathListObj);

            if (Build.VERSION.SDK_INT >= 23) {
                List<File> list = (List<File>) nativeLibraryObj;
                for (File file : list) {
                    if (new File(file.getAbsolutePath() + "/" + soName).exists()) {
                        return true;
                    }
                }
            } else {
                File[] fileArr = (File[]) nativeLibraryObj;
                for (File file : fileArr) {
                    if (new File(file.getAbsolutePath() + "/" + soName).exists()) {
                        return true;
                    }
                }
            }
        } catch (Throwable e) {
            // #debug
            e.printStackTrace();
        }
        return false;
    }
}