Skip to content

Instantly share code, notes, and snippets.

@yolapop
Last active July 19, 2017 13:02
Show Gist options
  • Save yolapop/94d0d82cc3734cc8241abfff90cb043e to your computer and use it in GitHub Desktop.
Save yolapop/94d0d82cc3734cc8241abfff90cb043e to your computer and use it in GitHub Desktop.
Code snippet for app launch optimization
public class BaseFragment extends Fragment {
@Override
public void onResume() {
super.onResume();
MyApplication.get().setAppIsReady(true);
}
}
/**
* Time consuming tasks in global initialization should be run later so it doesn't block
* first render of our Activity
*/
public class MyApplication extends Application {
public static MyApplication instance;
private volatile boolean appIsReady = false;
private volatile boolean once = false;
private volatile List<Runnable> onReadyRunnable = new ArrayList<>();
public static MyApplication get() {
return instance;
}
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
try {
MultiDex.install(this);
} catch (RuntimeException ignored) {
}
}
public void onCreate() {
super.onCreate();
instance = this;
delayAfterAppsReady(() -> {
FacebookSdk.sdkInitialize(getApplicationContext());
// you can add more tasks to be delayed here
});
}
public synchronized void delayAfterAppsReady(Runnable runnable) {
if (appIsReady) {
AndroidUtils.runOnBg(runnable);
} else {
onReadyRunnable.add(runnable);
}
}
public synchronized void setAppIsReady(boolean appIsReady) {
if (once) return;
if (appIsReady && onReadyRunnable != null) {
once = true;
AndroidUtils.runOnBg(() -> {
this.appIsReady = appIsReady;
final List<Runnable> runnables = new ArrayList<>(onReadyRunnable);
onReadyRunnable = null;
for (Runnable run : runnables) {
run.run();
}
});
}
}
}
public class MyFragment extends BaseFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApplication.get().delayAfterAppsReady(() -> {
// another additional tasks to be run after app is ready
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment