I have a work around, without coding the snackbar in all the activities onCreate()
method.
We can use the application class to call the BroadcastReciever
.
As below code.
public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
public static Activity appactivity;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
}
@Override
public void onActivityResumed(Activity activity) {
appactivity = activity;//here we get the activity
Intent i = new Intent(this, InternetConnectionInformation.class);
sendBroadcast(i);//here we are calling the broadcastreceiver to check connection state.
}
}
Now we can use our BroadcastReceiver class to show snackbar as well
public class InternetConnectionInformation extends BroadcastReceiver{
static Snackbar snackbar; //make it as global
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetworkInfo == null || !activeNetworkInfo.isConnected()) {
InternetConnectionInformation.snack(null, 0, "Network Connection failed.",context.getApplicationContext());
}else{
InternetConnectionInformation.hideSnackbar();
}
}
public static void snack (HashMap<String,View.OnClickListener> actions,int priority,String message,Context context) {
if(MyApplication.appactivity != null){
snackbar = Snackbar.make(MyApplication.appactivity.findViewById(android.R.id.content), message, Snackbar.LENGTH_INDEFINITE);//MyApplication.appactivity from Application class.
if (actions != null) {
Iterator iterator = actions.entrySet().iterator();
snackbar.setDuration(Snackbar.LENGTH_INDEFINITE);
while (iterator.hasNext()) {
Map.Entry pair = (Map.Entry) iterator.next();
snackbar.setAction((String) pair.getKey(), (View.OnClickListener) pair.getValue());
iterator.remove(); // avoids a ConcurrentModificationException
}
}
switch (priority) {
case 0:
snackbar.getView().setBackgroundColor(context.getResources().getColor(R.color.accentPink));
break;
case 1:
snackbar.getView().setBackgroundColor(Color.parseColor("#66ccff"));
break;
case 2:
snackbar.getView().setBackgroundColor(Color.parseColor("#66ff33"));
break;
}
snackbar.show();
}
}
private static void hideSnackbar(){
if(snackbar !=null && snackbar.isShown()){
snackbar.dismiss();
}
}
}
To hide the snackbar we need to check the connectivity state. So the BroadcastReceiver is registered in the Manifest
<receiver android:name="your.package.name.InternetConnectionInformation">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
This works fine and is tested. Hope it will help some.