java - 确保 Android 应用程序在单个进程中运行

标签 java android sqlite firebase multiprocessing

由于应用程序在多个进程中打开,我们最近开始在我们的 Android 应用程序中遇到崩溃。几个不同的错误指向这一点。例如这个错误:

com.google.firebase.database.DatabaseException: Failed to gain exclusive lock to Firebase Database's offline persistence. This generally means you are using Firebase Database from multiple processes in your app. Keep in mind that multi-process Android apps execute the code in your Application class in all processes, so you may need to avoid initializing FirebaseDatabase in your Application class. If you are intentionally using Firebase Database from multiple processes, you can only enable offline persistence (i.e. call setPersistenceEnabled(true)) in one of them.

我们也看到了来自 SQLite 和 H2 的类似错误。这是一个新问题,我们还没有明确允许运行多个进程。我们的 AndroidManifest.xml 中没有指定自定义 android:process 属性。

我怀疑是某些第三方库导致的。如何确定多个进程的根本原因以及如何预防?

我们的另一个应用程序正在通过 ContentProvider 连接到此应用程序。起初我认为它具有 android:multiprocess="true" 是罪魁祸首,但将其更改为“false”并没有帮助。我仍然怀疑另一个应用程序以某种方式触发了新进程的创建。这是 ContentProvider 的定义方式:

  <provider
        android:name=".DegooContentProvider"
        android:authorities="${applicationId}.DegooContentProvider"
        android:exported="true"
        android:protectionLevel="signature"
        android:multiprocess="false">
    </provider>

最佳答案

如果有外部进程,你可以检查你的应用程序类。这是一个例子:

public class MyApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        if (!isMainProcess()) {
            // Do not call thread unsafe logic. Just return
            return;
        }
        // Thread unsafe logic.
        ...
    }

    private boolean isMainProcess() {
        int pid = android.os.Process.myPid();
        ActivityManager manager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo processInfo : manager.getRunningAppProcesses()) {
            String currentProcName = processInfo.processName;
            if (processInfo.pid == pid) {
                if (TextUtils.equals(currentProcName, BuildConfig.APPLICATION_ID)) {
                    return true;
                }
            }
        }
        return false;
    }
}

关于java - 确保 Android 应用程序在单个进程中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51734385/

相关文章:

java - 在单个查询中使用 FK 更新现有 JPA 子实体

java - OnClickListener super

android - 一个可以将项目 rebase 到 Google AOSP 的 Gerrit 实例?

Android SQLite 数据库 onCreate 错误

Java:查找最长的连续相同字符数组

java - 在 AnyLogic 中模拟人口密度

java - 如何在没有初始动画的情况下更新 ListView 内的 SpeedView?

android.database.sqlite.SQLITeException : no such table: admin while compiling: INSERT INTO . ..等

java - Java 中 PHP PDO 的等价物

java - RuntimeException : Package jdk. 模块 jrt.fs 和模块 java.base 中的 internal.jimage.decompressor