java - setURLStreamHandlerFactory 和 "java.lang.Error: Factory already set"

标签 java android

我遇到了一个意外错误,原因是在正在更新的 Android 应用程序中调用 URL.setURLStreamHandlerFactory(factory);

public class ApplicationRoot extends Application {

    static {
        /* Add application support for custom URI protocols. */
        final URLStreamHandlerFactory factory = new URLStreamHandlerFactory() {
            @Override
            public URLStreamHandler createURLStreamHandler(final String protocol) {
                if (ExternalProtocol.PROTOCOL.equals(protocol)) {
                    return new ExternalProtocol();
                }
                if (ArchiveProtocol.PROTOCOL.equals(protocol)) {
                    return new ArchiveProtocol();
                }
                return null;
            }
        };
        URL.setURLStreamHandlerFactory(factory);
    }

}

简介:

这是我的情况:我正在维护一个以企业方式使用的非市场应用程序。我的企业销售的平板电脑预装了由企业开发和维护的应用程序。这些预安装的应用程序不是 ROM 的一部分;它们作为典型的Unknown Source 应用程序安装。我们不会通过 Play 商店或任何其他市场进行更新。相反,应用程序更新由自定义 Update Manager 应用程序控制,该应用程序直接与我们的服务器通信以执行 OTA 更新。

问题:

我正在维护的这个 Update Manager 应用程序有时需要自行更新。应用程序更新后立即通过 android.intent.action.PACKAGE_REPLACED 广播重新启动,我在 AndroidManifest 中注册了该广播。但是,在更新后立即重新启动应用程序时,我偶尔会收到此 Error

java.lang.Error: Factory already set
    at java.net.URL.setURLStreamHandlerFactory(URL.java:112)
    at com.xxx.xxx.ApplicationRoot.<clinit>(ApplicationRoot.java:37)
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(Class.java:1208)
    at android.app.Instrumentation.newApplication(Instrumentation.java:996)
    at android.app.Instrumentation.newApplication(Instrumentation.java:981)
    at android.app.LoadedApk.makeApplication(LoadedApk.java:511)
    at android.app.ActivityThread.handleReceiver(ActivityThread.java:2625)
    at android.app.ActivityThread.access$1800(ActivityThread.java:172)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1384)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:146)
    at android.app.ActivityThread.main(ActivityThread.java:5653)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
    at dalvik.system.NativeStart.main(Native Method)

请注意,大多数情况下,应用程序会正常重启。但是,每隔一段时间,我就会收到上述错误。我很困惑,因为我调用 setURLStreamHandlerFactoryonly 地方就在这里,它是在 static block 中完成的,我认为这是正确的 - 虽然是正确的如果我错了,我只调用一次,如果第一次加载 ApplicationRoot 类。但是,它似乎被调用了两次,导致上述错误。

问题:

炽热的 sams 中发生了什么?在这一点上我唯一的猜测是,更新的应用程序的虚拟机/进程与正在更新的以前安装的应用程序相同,所以当 static new ApplicationRoot block 被调用,old ApplicationRoot 设置的 URLStreamHandlerFactory 仍然是“活跃的”。这可能吗?我怎样才能避免这种情况?看到它并不总是发生,这似乎是某种竞争条件;也许在 Android 的 APK 安装程序中?谢谢,

编辑:

根据要求提供其他代码。这是处理广播的 list 部分

<receiver android:name=".OnSelfUpdate" >
    <intent-filter>
        <action android:name="android.intent.action.PACKAGE_REPLACED" />
        <data android:scheme="package" />
    </intent-filter>
</receiver>

还有 BroadcastReceiver 本身

public class OnSelfUpdate extends BroadcastReceiver {

    @Override
    public void onReceive(final Context context, final Intent intent) {
        /* Get the application(s) updated. */
        final int uid = intent.getIntExtra(Intent.EXTRA_UID, 0);
        final PackageManager packageManager = context.getPackageManager();
        final String[] packages = packageManager.getPackagesForUid(uid);

        if (packages != null) {
            final String thisPackage = context.getPackageName();
            for (final String pkg : packages) {
                /* Check to see if this application was updated. */
                if (pkg.equals(thisPackage)) {
                    final Intent intent = new Intent(context, MainActivity.class);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intent);
                    break;
                }
            }
        }
    }

}

最佳答案

加载类时会执行静态 block - 如果由于某种原因(例如更新时)重新加载了类,它将再次执行。

在您的情况下,这意味着您设置的上次加载时间的 URLStreamHandlerFactory 将保留。

除非您更新了 URLStreamHandlerFactory,否则这并不是真正的问题。

有两种方法可以解决这个问题:

  1. 捕获错误,继续你的快乐之路,忽略你仍在使用旧工厂的事实。

  2. 实现一个非常简单的包装器,该包装器委托(delegate)给您可以替换且无需更改的另一个URLStreamHandlerFactory。你会在这里遇到与包装器相同的问题,因此你需要在该包装器上捕获 Error 或将其与选项 3 结合使用。

  3. 跟踪您是否已经使用系统属性安装了处理程序。

代码:

public static void maybeInstall(URLStreamHandlerFactory factory) {
    if(System.getProperty("com.xxx.streamHandlerFactoryInstalled") == null) {
        URL.setURLStreamHandlerFactory(factory);
        System.setProperty("com.xxx.streamHandlerFactoryInstalled", "true");
    }
}
  1. 使用反射强制替换。我完全不知道为什么您只能设置一次 URLStreamHandlerFactory - 这对我来说毫无意义 TBH。

代码:

public static void forcefullyInstall(URLStreamHandlerFactory factory) {
    try {
        // Try doing it the normal way
        URL.setURLStreamHandlerFactory(factory);
    } catch (final Error e) {
        // Force it via reflection
        try {
            final Field factoryField = URL.class.getDeclaredField("factory");
            factoryField.setAccessible(true);
            factoryField.set(null, factory);
        } catch (NoSuchFieldException | IllegalAccessException e1) {
            throw new Error("Could not access factory field on URL class: {}", e);
        }
    }
}

Oracle 的 JRE 上的字段名称是 factory,在 Android 上可能会有所不同。

关于java - setURLStreamHandlerFactory 和 "java.lang.Error: Factory already set",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30267447/

相关文章:

java - 为什么会出现 IllegalMonitorStateException?

java - 当应用程序关闭时,我可以不断地从服务类中收听数据变化吗?

java - 为什么从 Android 应用程序访问数据库不安全?

java - 如何在Java中处理JSON(Android Studio)

android - 有任何理由转发锁定免费应用程序吗?

Java 检索 JSON 中嵌套字段的方法

java - 获取返回 ArrayList<String[]> 的函数的值

java - Java 8 流的不干扰要求

java - 开始时关闭 Android 键盘

android - 带有 Overlay 的 MapView 存在性能问题