网络实时监测广播类

package com.example.receiver;


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




/**
 * 网络实时监测广播
 * 
 * @author pei
 * @version1.0
 * @create 2016-04-01
 * @description
 * 权限    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
 * 初始化 
 *     NetworkReceiver networkReceiver=new NetworkReceiver(Mainactivity.this);
 *     networkReceiver.registerReceiver();
 * 销毁
 *     networkReceiver.onDestroy(); 
 */
public class NetworkReceiver extends BroadcastReceiver{
    
private Context mContext;

public NetworkReceiver(Context context){
this.mContext=context;


/**注册广播**/
    public void registerReceiver() {
        IntentFilter intentfilter = new IntentFilter();
        intentfilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        mContext.registerReceiver(NetworkReceiver.this, intentfilter);
    }
@Override
public void onReceive(Context arg0, Intent arg1) {
ConnectivityManager connectionManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectionManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isAvailable()) {
Toast.makeText(mContext, "network is available",0).show();
} else {
Toast.makeText(mContext, "network is unavailable",0).show();
}


}

public void onDestroy(){
mContext.unregisterReceiver(NetworkReceiver.this);
}
}

你可能感兴趣的:(android,Broadcast)