android 实时监控网络改变

第一步:写一个广播接收类

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

public class NetworkChangeBroadcast extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("NetworkChangeBroadcast", "network changed!");

        boolean isNetworkAvailable = false, isWifiAvailable = false, isMobileAvailable = false;
        ConnectivityManager connectivityManager = (ConnectivityManager)
                context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null) {
            isNetworkAvailable = networkInfo.isAvailable();
            isWifiAvailable = networkInfo.isAvailable() && (networkInfo.getType() == ConnectivityManager.TYPE_WIFI);
            isMobileAvailable = networkInfo.isAvailable() && (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE);
        }

        if (isNetworkAvailable) {
            if (isWifiAvailable) {
                Toast.makeText(context, "当前网络状态:Wifi 可用", Toast.LENGTH_SHORT).show();
            } else if (isMobileAvailable) {
                Toast.makeText(context, "当前网络状态:移动网络可用", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(context, "当前网络状态:网络不可用", Toast.LENGTH_SHORT).show();
        }
    }
}

第二步:在需要监控的类中引用,一般为activity的基类,动态注册广播监听网络的变化,在onCreate中注册,onDestroy中反注册


import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class BaseActivity extends AppCompatActivity {

    private NetworkChangeBroadcast networkChangeBroadcast = null;

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

        networkChangeBroadcast = new NetworkChangeBroadcast();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        registerReceiver(networkChangeBroadcast, intentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(networkChangeBroadcast);
    }
}

最后注意:访问网络状态需要在Manifest中添加网络访问权限         android.permission.ACCESS_NETWORK_STATE

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值