我希望在互联网关闭时显示全屏图像,以便用户无法使用该应用,因为他没有互联网连接。我想使用像这样的广播接收器:
public class ConnectivityChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null)
if (extras.get("EXTRA_NO_CONNECTIVITY") == true) {
//show splash screen
}
}
}
if指令为true时显示启动画面。
请告诉我这是否正确以及如何显示启动画面。
答案 0 :(得分:1)
你走在正确的轨道上。这就是你如何做到的:
1:如果网络发生变化,则创建带有回调的NetworkChangeReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
private NetworkLostCallback mNetworkLostCallback;
public interface NetworkLostCallback {
public void onNetworkLost();
public void onNetworkRegained();
}
public void setNetworkLostCallback(NetworkLostCallback callback) {
mNetworkLostCallback = callback;
}
@Override
public void onReceive(final Context context, final Intent intent) {
if (mNetworkLostCallback != null) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null
&& (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE || activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)) {
mNetworkLostCallback.onNetworkRegained();
} else {
mNetworkLostCallback.onNetworkLost();
}
}
}
}
2:注册接收器和回调
mNetworkChangeReceiver = new NetworkChangeReceiver();
mNetworkChangeReceiver.setNetworkLostCallback(this);
IntentFilter networkFilter = new IntentFilter();
networkFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(mNetworkChangeReceiver, networkFilter);
3:监听更改并在网络丢失时显示对话框。
public void onNetworkLost() {
Fragment f = getFragmentManager().findFragmentByTag(DisconnectedDialog.class.getSimpleName());
if (f == null) {
DisconnectedDialog dialog = DisconnectedDialog.newInstance();
dialog.setCancelable(false);
dialog.show(getFragmentManager(), DisconnectedDialog.class.getSimpleName());
}
}
完成。
如果您打开对话框或其他活动,则取决于您。