4

Snackbars 通过在屏幕底部显示一条简短消息来提供有关操作的轻量级反馈。Snackbars 可以包含一个动作。

Android 还提供了 toast,主要用于系统消息传递。Toasts 类似于小吃店,但不包含动作并且不能从屏幕上滑出。

我的问题

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();
    }
}

是否可以显示Snackbar一个BroadcastReceiverlike Toast

4

4 回答 4

7

是否可以像 Toast 一样在 BroadcastReceiver 中显示 snakbars?

BroadcastReceiver活动或片段注册的,通过registerReceiver(),可以要求活动或片段显示小吃吧。

manifest-registeredBroadcastReceiver没有 UI,因此它没有地方显示一个snackbar。它可以做的是在进程中的事件总线上发布一个事件(例如,LocalBroadcastManagergreenrobot 的 EventBus,Square 的 Otto),让您在前台的任何 UI 都知道收到了广播。如果 UI 层收到消息,则该活动或片段可以显示一个快餐栏。如果未拾取事件总线事件,您可能会Notification在适当的情况下将 a 显示为后备。

于 2015-07-15T11:16:31.900 回答
5

我的工作代码....

public abstract  class TestReceiver  extends BroadcastReceiver {
    @Override   
    public void onReceive(final Context context, final Intent intent) {
        onNetworkChange();
    } 

    protected abstract void onNetworkChange();
}

在主要活动中

public class MainActivity extends Activity  {

    public void onCreate() {
        ...  mReceiver = new TestReceiver () {
            @Override
            protected void onNetworkChange() {
            snackbar = Snackbar.make(Clayout, "Please check your internet connection and try again", Snackbar.LENGTH_SHORT);
            snackbar.setAction("X", snackbarClickListener);snackbar.setActionTextColor(Color.GREEN);
            ColoredSnackbar coloredsnakbar=new ColoredSnackbar();
            coloredsnakbar.confirm(snackbar).show();
            }
        };      
    }
}
于 2015-07-21T06:28:13.080 回答
3

正如@CommonsWare 先生所说,在 UI 连接的位置BroadcastReceiver和连接位置之间必须有一些传递机制。Activity/Fragment

我试图在interface这里添加例如:

public class TestReceiver extends BroadcastReceiver {

    private DoSomethingInterface callback1;

    public TestReceiver() {
    }

    @Override
    public void onReceive(final Context context, final Intent intent) {
        // pass content text to show in SnackBar
        if(callback1 != null) {
            callback1.passText("status");
        } else {
            Log.e("log","callback from UI is not registered yet..");
        }
    }

    public void registerReceiver(DoSomethingInterface receiver) {
         this.callback1 = receiver;
    }

    public interface DoSomethingInterface {
        public void passText(String text);
    }
}

在显示 SnackBar 的 Activity 或 Fragment 中实现DoSomethingInterface。确保您需要添加CoordinatorLayout显示SnakeBar

public class MainActivity extends Activity implements DoSomethingInterface {

public void onCreate() {
    ...
    // pass reference to interface from onCreate()
    BroadcastReceiver mReceiver = new TestReceiver();
    mReceiver.registerReceiver(this);
    ...
}

    @Override
    public void passText(String text) {
        Snackbar.make(<reference to your coordinator layout>, "text", Snackbar.LENGTH_LONG)
                    .setAction("Ok", <listener>)
                    .setActionTextColor(Color.GREEN)
                    .show();
于 2015-07-15T11:51:19.093 回答
1

我有一个解决方法,没有在所有活动onCreate()方法中对小吃店进行编码。

我们可以使用应用程序类来调用BroadcastReciever. 如下代码。

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.
    }
}

现在我们也可以使用我们的 BroadcastReceiver 类来显示snackbar了

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();
            }
        }
    }

要隐藏快餐栏,我们需要检查连接状态。所以 BroadcastReceiver 注册在Manifest

<receiver android:name="your.package.name.InternetConnectionInformation">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
            </intent-filter>
        </receiver>

这工作正常并经过测试。希望它会有所帮助。

于 2016-04-26T06:59:06.377 回答