我有一个解决方法,没有在所有活动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>
这工作正常并经过测试。希望它会有所帮助。