Skip to content

Instantly share code, notes, and snippets.

@vellrya
Last active March 4, 2024 13:35
Show Gist options
  • Save vellrya/6ab5d915f1002a8e1ae3205ba715f0d7 to your computer and use it in GitHub Desktop.
Save vellrya/6ab5d915f1002a8e1ae3205ba715f0d7 to your computer and use it in GitHub Desktop.
Fix "FirebaseApp is not initialized in this process"
class App : Application() {
var mainProcess = false
var metricaProcess = false
override fun onCreate() {
val processName = ProcessUtil.getProcessName(this)
mainProcess = processName==packageName
metricaProcess = processName.contains(":AppMetrica") || processName.contains(":Metrica")
if (!metricaProcess) { // you do not need to initialise anything manually inside the Metrica process
if (!mainProcess) {
// if you created the service yourself in a separate process (via android:process=":Something"), you should manually initialise Firebase in that process.
FirebaseApp.initializeApp(this)
}
// put old onCreate code here, e.g:
// FirebaseCrashlytics.getInstance().setUserId("someId")
// if (mainProcess) MobileAds.initialize(this) { } // you probably don't want ads in the background process
// ...
}
super.onCreate()
}
}
public class ProcessUtil {
//code from androidx.work.impl.utils
public static String getProcessName(@NonNull Context context) {
if (SDK_INT >= 28) {
return Application.getProcessName();
}
// Try using ActivityThread to determine the current process name.
try {
@SuppressLint("PrivateApi") Class<?> activityThread = Class.forName(
"android.app.ActivityThread",
false,
ProcessUtils.class.getClassLoader());
final Object packageName;
Method currentProcessName = activityThread.getDeclaredMethod("currentProcessName");
currentProcessName.setAccessible(true);
packageName = currentProcessName.invoke(null);
if (packageName instanceof String) {
return (String) packageName;
}
} catch (Throwable exception) {
}
// Fallback to the most expensive way
int pid = Process.myPid();
ActivityManager am =
(ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
if (am != null) {
List<ActivityManager.RunningAppProcessInfo> processes = am.getRunningAppProcesses();
if (processes != null && !processes.isEmpty()) {
for (ActivityManager.RunningAppProcessInfo process : processes) {
if (process.pid == pid) {
return process.processName;
}
}
}
}
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment