【发布时间】:2017-08-04 12:26:00
【问题描述】:
我正在使用 Firebase。我的应用程序无法使用的某些功能处于离线状态(或者将来可能会使用离线模式)。那么我如何检测到连接丢失,或者 wifi/otherNetwork 在运行活动时关闭。我关注了这个doc,但只在启动应用程序时使用......不适用于正在运行的应用程序。所以你们对我的问题有什么解决方案吗?
【问题讨论】:
标签: android firebase firebase-realtime-database
我正在使用 Firebase。我的应用程序无法使用的某些功能处于离线状态(或者将来可能会使用离线模式)。那么我如何检测到连接丢失,或者 wifi/otherNetwork 在运行活动时关闭。我关注了这个doc,但只在启动应用程序时使用......不适用于正在运行的应用程序。所以你们对我的问题有什么解决方案吗?
【问题讨论】:
标签: android firebase firebase-realtime-database
使用此方法检查应用中的互联网连接:
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
Intent networkStateIntent = new Intent(Constants.NETWORK_AVAILABLE_ACTION);
networkStateIntent.putExtra(Constants.IS_NETWORK_AVAILABLE, isConnectedToInternet(context));
LocalBroadcastManager.getInstance(context).sendBroadcast(networkStateIntent);
}
public boolean isConnectedToInternet(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
//should check null because in airplane mode it will be null
if (netInfo != null && netInfo.isConnected()) {
return true;
} else {
return false;
}
}
像这样在清单文件中注册接收方:
<receiver android:name=".utils.NetwrokConnection.NetworkChangeReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
在要检查连接的活动中使用此方法:
public void networkConnection() {
IntentFilter intentFilter = new IntentFilter(Constants.NETWORK_AVAILABLE_ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
boolean isNetworkAvailable = intent.getBooleanExtra(Constants.IS_NETWORK_AVAILABLE, false);
Dialogs.getInstance().showSnackbar(activity,(View) rootlayout, isNetworkAvailable);
}
}, intentFilter);
}
还要在清单文件中添加权限:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
【讨论】: