静态注册广播监听网络变化

常用的IM聊天App中都会判断网络连接是否可用,今天我们就用静态注册注册广播来监听网络的变化:首先申请网络权限


然后在mainifest文件静态注册广播:

  
            
                
            
        

这样当网络变化的时候,就能监听到相应的网络情况:

package com.example.administrator.broadcastreceiver;

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 NetWorkChangeReceiver extends BroadcastReceiver {
    public NetWorkChangeReceiver() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO: This method is called when the BroadcastReceiver is receiving
        //Toast.makeText(context,"netChanged!",Toast.LENGTH_LONG).show();
       ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if(networkInfo !=null && networkInfo.isAvailable())
        {
            Toast.makeText(context,"isAvailable!",Toast.LENGTH_LONG).show();
        }else
        {
            Toast.makeText(context,"unAvailable!",Toast.LENGTH_LONG).show();
        }
    }
}
OK了,静注册广播监听网络变化已实现。

你可能感兴趣的:(Android)