I have an android app which has an internet connectivity service. The service shows a snackbar whenever the application comes online or goes offline. The services works fine, however the when accessing the MainActivity's snackbar or the relative layout on which I will show the snackbar, I get null values. Below is the implementation of the callback from the background service, this method is written inside the mainactivity:
public void hasInternetConnection() {
if (!hasInternetMessageShown) {
showSnackBar("App is online", false);
}
}
private void showSnackBar(String message, boolean shouldStick) {
if (snack != null && snack.isShown()) {
snack.dismiss();
}
snack = Snackbar.make(rootView, message, Snackbar.LENGTH_SHORT);
snack.getView().setBackgroundColor(activity.getResources().getColor(R.color.blue_light));
TextView textView = snack.getView().findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(activity.getResources().getColor(R.color.orange));
Typeface typeface = ResourcesCompat.getFont(activity, R.font.semibold);
textView.setTypeface(typeface, Typeface.NORMAL);
if (shouldStick)
snack.setDuration(BaseTransientBottomBar.LENGTH_INDEFINITE);
snack.show();
}
The above code only works if I keep the instance of snack and activity static. Which I don't want to do as it will trigger memory leak. Please help me here so that I can handle this efficiently.
Thanks!!
Please try to send a local broadcast on activity from your service and then try to update your snack bar.