Is there any possible way to close android snackbar (LENGTH_INDEFINITE)automatically while internet connected without any action?

RAMESH picture RAMESH · Jan 31, 2016 · Viewed 7k times · Source

I have displayed android snack bar with INDEFINITE LENGTH but how to close snack bar with out any action or duration while Internet connected . I have to check internet connected or not.after internet connected snack bar will be closed automatically without any action or duration.If anybody knows kindly help me.

here is my code

public static void snack (HashMap<String,View.OnClickListener> actions,int priority,String message,Activity context){
    Snackbar B = Snackbar.make(context.findViewById(android.R.id.content), message, Snackbar.LENGTH_LONG);
    if(actions!=null){
    Iterator iterator = actions.entrySet().iterator();
        B.setDuration(Snackbar.LENGTH_INDEFINITE);
    while (iterator.hasNext()) {
        Map.Entry pair = (Map.Entry)iterator.next();
        B.setAction((String)pair.getKey(),(View.OnClickListener)pair.getValue());
        iterator.remove(); // avoids a ConcurrentModificationException
    }}
    switch (priority)
    {
        case 0:
            B.getView().setBackgroundColor(context.getResources().getColor(R.color.color_pinkbutton));
            break;
        case 1:
            B.getView().setBackgroundColor(Color.parseColor("#66ccff"));
            break;
        case 2:
            B.getView().setBackgroundColor(Color.parseColor("#66ff33"));
            break;
    }
    B.show();

after calling above mentioned method using the activity is as follows

If (NetworkCheck.isNetworkAvailable(this) == false) {
    MyApplication.snack(null, 0, "Network Connection failed.",class.this);
else

Answer

Farhan picture Farhan · Sep 7, 2016

I have made this singleton utility class. It kept the application class cleaner and best for future maintainability of snack bars.

public class SnackBarUtils {
    private static SnackBarUtils mInstance = null;
    private Snackbar mSnackBar;

    private SnackBarUtils() {

    }

    public static SnackBarUtils getInstance() {
        if (mInstance == null) {
            mInstance = new SnackBarUtils();
        }
        return mInstance;
    }

    public void hideSnackBar() {
        if (mSnackBar != null) {
            mSnackBar.dismiss();
        }
    }

    public void showProblemSnackBar(final Activity activity, final String message) {
        mSnackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE);
        // Changing action button text color
        View sbView = mSnackBar.getView();
        TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
        textView.setTextColor(Color.YELLOW);
        mSnackBar.show();
    }
}