1.创建一个类,继承BroadcastReceiver
public class NetStats extends BroadcastReceiver {
private View popView;
private PopupWindow popupWindow;
private ImageView shuaxin;
@Override
public void onReceive(Context context, Intent intent) {
popView = LayoutInflater.from(context).inflate(R.layout.pop_netstate_view, null);
popupWindow = new PopupWindow(popView,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT,true);
shuaxin = popView.findViewById(R.id.shuaxin);
ConnectivityManager manager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo gprs = manager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
NetworkInfo wifi = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(!gprs.isConnected() && !wifi.isConnected())
{
popupWindow.showAtLocation(popView,Gravity.NO_GRAVITY,0,0);
}
else {
Toast.makeText(context,"网络连接成功",+0).show();
}
shuaxin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!gprs.isConnected() && !wifi.isConnected())
{
//popupWindow.showAtLocation(popView,Gravity.NO_GRAVITY,0,0);
Toast.makeText(context, "仍无网络!", Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(context,"网络连接成功",+0).show();
popupWindow.dismiss();
}
}
});
}
2.清单文件里注册广播
<receiver android:name=".app.utils.NetStats">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>
3.PopupWindowd 的布局
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#F6F6F6">
<ImageView
android:id="@+id/notNetImg_fragmentFilm"
android:layout_centerHorizontal="true"
android:layout_marginTop="170dp"
android:layout_width="200dp"
android:layout_height="200dp"
android:background="@drawable/ww_one"/>
<TextView
android:layout_below="@+id/notNetImg_fragmentFilm"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="糟糕,网络不给力啊! 请检查网络!"
android:textColor="#8c8c8c"
android:id="@+id/file"
android:textSize="14sp"/>
<ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:src="@drawable/shuaxin"
android:layout_below="@id/file"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:id="@+id/shuaxin"/>
</RelativeLayout>
4.在Activity里写
NetStats receiver = new NetStats();
IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
getActivity().registerReceiver(receiver, filter);
receiver.onReceive(getActivity(), null);