Android中Firebase与AppMetrica冲突致SQLite数据库锁定问题求助
This error pops up because Yandex AppMetrica runs in a separate background process, and if your Firebase initialization code executes across all app processes (including Metrica's), two distinct processes will try to access Firebase's underlying SQLite database at the same time. SQLite doesn't handle cross-process concurrent write access smoothly, leading to the database is locked exception and those persistent "App has stopped" prompts.
Here are actionable fixes to resolve this:
1. Restrict Firebase Initialization to Your Main Process
Firebase doesn't need to be initialized in AppMetrica's background process. Modify your Application class to only set up Firebase when running in your app's main process:
import android.app.ActivityManager; import android.content.Context; import android.os.Build; import android.os.Process; import com.google.firebase.FirebaseApp; import com.yandex.metrica.YandexMetrica; import com.yandex.metrica.YandexMetricaConfig; public class MyApp extends Application { @Override public void onCreate() { super.onCreate(); // Initialize Firebase ONLY in the main app process if (isMainProcess()) { FirebaseApp.initializeApp(this); } // Initialize AppMetrica normally (it will run in its dedicated process) YandexMetricaConfig config = YandexMetricaConfig.newBuilder("YOUR_METRICA_API_KEY") .build(); YandexMetrica.activate(getApplicationContext(), config); YandexMetrica.enableActivityAutoTracking(this); } private boolean isMainProcess() { String packageName = getPackageName(); String processName = getCurrentProcessName(); return packageName.equals(processName); } private String getCurrentProcessName() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { return Application.getProcessName(); } // Fallback for older Android versions ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE); for (ActivityManager.RunningAppProcessInfo processInfo : activityManager.getRunningAppProcesses()) { if (processInfo.pid == Process.myPid()) { return processInfo.processName; } } return null; } }
2. Verify AppMetrica's Process Setup (Optional)
You don't need to alter AppMetrica's default process configuration—just ensuring Firebase isn't initialized in its process is sufficient. If you want to double-check, confirm the Metrica service in your AndroidManifest.xml doesn't trigger Firebase initialization (it won't, as long as you follow step 1).
Why This Fix Works:
- Your main process handles all Firebase operations, accessing the SQLite database without conflicts.
- AppMetrica's process runs independently, never attempting to access Firebase's database, so the lock issue is eliminated entirely.
- Your app will stop showing the "App has stopped" prompts, while both Firebase and AppMetrica continue to function as intended.
内容的提问来源于stack exchange,提问作者TopAd Studio

