Snackbars provide lightweight feedback about an operation by showing a brief message at the bottom of the screen. Snackbars can contain an action.
Android also provides a toast, primarily used for system messaging. Toasts are similar to snackbars but do not contain actions and cannot be swiped off screen.
My question
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class TestReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Toast.makeText(context, "status", Toast.LENGTH_LONG).show();
}
}
Is it posible to show a Snackbar
in a BroadcastReceiver
like Toast
?
A
BroadcastReceiver
registered by an activity or fragment, viaregisterReceiver()
, could ask the activity or fragment to show a snackbar.A manifest-registered
BroadcastReceiver
has no UI, and hence it has no place to show a snackbar. What it could do is post an event on an in-process event bus (e.g.,LocalBroadcastManager
, greenrobot's EventBus, Square's Otto), to let whatever UI of yours that is in the foreground know that a broadcast was received. If the UI layer receives the message, that activity or fragment can show a snackbar. If the event bus event was not picked up, you can perhaps show aNotification
as a fallback, if appropriate.my working code....
in mainactivity
As @CommonsWare sir told, there has to be some passing mechanism between
BroadcastReceiver
andActivity/Fragment
where UI is attached.I have tried to add
interface
for example here :Implement the
DoSomethingInterface
in your Activity or Fragment where you are showing SnackBar. Make sure that you need to addCoordinatorLayout
for displayingSnakeBar
: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.Now we can use our BroadcastReceiver class to show snackbar as well
To hide the snackbar we need to check the connectivity state. So the BroadcastReceiver is registered in the
Manifest
This works fine and is tested. Hope it will help some.