安卓通过广播实时监听当前网络状况

需求:

当网络断开或者连接上的时候,需要你的APP作出一定的响应,有时候还需要判断当前网络的类型,wifi或者移动数据…

分析:

  1. 网络发生变化系统会发送广播
  2. 通过注册一个广播接收器来接收广播
  3. 判断当前变化的网络是什么状态(wifi,移动数据,无网络)
  4. 最后一个接口回调当前的状态·瞬间爆炸完成单杀

话不多说开始撸码:

第一步:检查网络状态的类型
需要设置权限–允许查看网络状态

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class NetUtil {
    /**
     * 没有连接网络
     */
    private static final int NETWORK_NONE = -1;
    /**
     * 移动网络
     */
    private static final int NETWORK_MOBILE = 0;
    /**
     * 无线网络
     */
    private static final int NETWORK_WIFI = 1;

    public static int getNetWorkState(Context context) {
        // 得到连接管理器对象
        ConnectivityManager connectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        if (activeNetworkInfo != null && activeNetworkInfo.isConnected()) {

            if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_WIFI)) {
                return NETWORK_WIFI;
            } else if (activeNetworkInfo.getType() == (ConnectivityManager.TYPE_MOBILE)) {
                return NETWORK_MOBILE;
            }
        } else {
            return NETWORK_NONE;
        }
        return NETWORK_NONE;
    }
}

第二步:创建状态回调接口

public interface NetEvent {
    void onNetChange(int netMobile);
}

第三步:创建广播接收器

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;

public class NetBroadcastReceiver extends BroadcastReceiver {

    private NetEvent netEvent;

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
            //检查网络状态的类型
            int netWrokState = NetUtil.getNetWorkState(context);
            if (netEvent != null)
                // 接口回传网络状态的类型
                netEvent.onNetChange(netWrokState);
        }
    }

    public void setNetEvent(NetEvent netEvent) {
        this.netEvent = netEvent;
    }

}

第四步:在Acitivity中动态注册广播,这里不能静态注册哦,原因你懂的

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import java.util.Date;

public class MainActivity extends AppCompatActivity implements NetEvent {

    /**
     * 网络状态
     */
    private int netMobile;

    private TextView mtvNet;

    /**
     * 监控网络的广播
     */
    private NetBroadcastReceiver netBroadcastReceiver;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mtvNet = (TextView) findViewById(R.id.tv_net);

    }

    @Override
    public void onStart() {
        super.onStart();
        //注册广播
        if (netBroadcastReceiver == null) {
            netBroadcastReceiver = new NetBroadcastReceiver();
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netBroadcastReceiver, filter);
            /**
             * 设置监听
             */
            netBroadcastReceiver.setNetEvent(this);
        }
    }

    @Override
    public void onNetChange(int netMobile) {
        this.netMobile = netMobile;
        isNetConnect();
    }

    private void isNetConnect() {
        mtvNet.append("\n" + new Date());
        switch (netMobile) {
            case 1://wifi

                mtvNet.append("\n当前网络类型:wifi");
                break;
            case 0://移动数据

                mtvNet.append("\n当前网络类型:移动数据");
                break;
            case -1://没有网络

                mtvNet.append("\n当前无网络");
                break;
        }

        mtvNet.append("\n------------------------------------------------------------------------------------------");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (netBroadcastReceiver != null) {
        //注销广播
            unregisterReceiver(netBroadcastReceiver);
        }
    }
}

activity_main.xml:

<ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tv_net"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
ScrollView>

效果图–由于是测试机,没有移动数据,就测了wifi

安卓通过广播实时监听当前网络状况_第1张图片

下载源码

你可能感兴趣的:(Android)