android网络连接的判断

1.网络连接是通过广播进行发送的

package ysl.netdemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.text.TextUtils;
import android.util.Log;

public class NetWorkBroadcastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {// 监听网络连接状态变化
			Log.i("ysl",
					"NetWorkBroadcastReceiver onReceive CONNECTIVITY_ACTION");
			String oldNetType = LetvBaseWebViewActivity.netType;
			String currentNetType = NetWorkTypeUtils
					.getNetTypeForWebView(context);
			String telecomOperators = NetWorkTypeUtils.getTelecomOperators(context);
			
			if (TextUtils.isEmpty(oldNetType)) {
				Log.i("ysl", "oldNetType为空!BaseWebView初始化有问题!");
			} else if (!oldNetType.equalsIgnoreCase(currentNetType)) {
				HashMap<String, Object> netMap = new HashMap<String, Object>();
				netMap.put("pre", oldNetType);
				netMap.put("now", currentNetType);
				Log.i("ysl", oldNetType+"-----------------"+currentNetType+"_________"+telecomOperators);
				netMap.put("result", 200);
				notifyAllObservers(netMap);
				LetvBaseWebViewActivity.netType = currentNetType;
			}else if (oldNetType.equalsIgnoreCase(currentNetType)) {
				Log.i("ysl", oldNetType+"=========="+currentNetType+"_________"+telecomOperators);
			}
		}
	}

	public interface NetWorkChangeObserver {
		void onNetTypeChange(HashMap<String, Object> netMap);
	}

	private static List<NetWorkChangeObserver> netWorkChangeObservers = new ArrayList<NetWorkChangeObserver>();

	public synchronized static void registerObserver(
			NetWorkChangeObserver observer) {
		if (!netWorkChangeObservers.contains(observer)) {
			netWorkChangeObservers.add(observer);
		}
	}

	public synchronized static void unRegisterObserver(
			NetWorkChangeObserver observer) {
		if (netWorkChangeObservers.contains(observer)) {
			netWorkChangeObservers.remove(observer);
		}
	}

	public void notifyAllObservers(HashMap<String, Object> netMap) {
		for (NetWorkChangeObserver observer : netWorkChangeObservers) {
			observer.onNetTypeChange(netMap);
		}
	}
}

2.注册广播接受者,就可以使用

NetWorkBroadcastReceiver receiver = new NetWorkBroadcastReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
		registerReceiver(receiver, filter);

3.这有一个判断网络的工具类,可直接使用

package ysl.netdemo;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.text.TextUtils;

public class NetWorkTypeUtils {

	private static final int NETTYPE_WIFI = 5;
	private static final int NETTYPE_2G = 2;
	private static final int NETTYPE_3G = 3;
	private static final int NETTYPE_4G = 4;
	private static final int NETTYPE_UNKOWN = 0;
	private static final int NETTYPE_NO = 1;
	private static final String China_Mobile = "中国移动";
	private static final String China_Unicom = "中国联通";
	private static final String China_Telecom = "中国电信";
	private static final String China_Unkown = "不知道";
	private static ConnectivityManager connectivityManager;
	private static NetworkInfo networkInfo;

	public static String getNetTypeForWebView(Context context) {
		String type = "unknown";
		
			int netGeneration = NetWorkTypeUtils.getNetGeneration(context);
			switch (netGeneration) {
			case NetWorkTypeUtils.NETTYPE_WIFI:
				type = "wifi";
				break;
			case NetWorkTypeUtils.NETTYPE_2G:
				type = "2G";
				break;
			case NetWorkTypeUtils.NETTYPE_3G:
				type = "3G";
				break;
			case NetWorkTypeUtils.NETTYPE_4G:
				type = "4G";
				break;
			case NetWorkTypeUtils.NETTYPE_UNKOWN:
				type = "unknown";
				break;
			case NetWorkTypeUtils.NETTYPE_NO:
				type = "none";
				break;
			}
		
		return type;
	}

	private static int getNetGeneration(Context context) {
		connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo != null && networkInfo.isAvailable()) {
			String typeName = networkInfo.getTypeName();
			if ("WIFI".equalsIgnoreCase(typeName)) {
				return NETTYPE_WIFI;
			} else if ("MOBILE".equalsIgnoreCase(typeName)) {
				TelephonyManager telephonyManager = (TelephonyManager) context
						.getSystemService(Context.TELEPHONY_SERVICE);
				switch (telephonyManager.getNetworkType()) {
				case TelephonyManager.NETWORK_TYPE_GPRS:
				case TelephonyManager.NETWORK_TYPE_EDGE:
				case TelephonyManager.NETWORK_TYPE_CDMA:
				case TelephonyManager.NETWORK_TYPE_1xRTT:
				case TelephonyManager.NETWORK_TYPE_IDEN:
					return NETTYPE_2G;
				case TelephonyManager.NETWORK_TYPE_UMTS:
				case TelephonyManager.NETWORK_TYPE_EVDO_0:
				case TelephonyManager.NETWORK_TYPE_EVDO_A:
				case TelephonyManager.NETWORK_TYPE_HSDPA:
				case TelephonyManager.NETWORK_TYPE_HSUPA:
				case TelephonyManager.NETWORK_TYPE_HSPA:
				case TelephonyManager.NETWORK_TYPE_EVDO_B:
				case TelephonyManager.NETWORK_TYPE_EHRPD:
				case TelephonyManager.NETWORK_TYPE_HSPAP:
					return NETTYPE_3G;
				case TelephonyManager.NETWORK_TYPE_LTE:

					return NETTYPE_4G;
				case TelephonyManager.NETWORK_TYPE_UNKNOWN:
					return NETTYPE_UNKOWN;
				default:
					return NETTYPE_UNKOWN;

				}

			}
		} else {
			return NETTYPE_NO;
		}
		return -1;
	}


	/**
	 * 判断为哪个运营商
	 */
	public static String getTelecomOperators(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		String imsi = "";
		if (networkInfo != null && networkInfo.isAvailable()) {
			TelephonyManager telephonyManager = (TelephonyManager) context
					.getSystemService(Context.TELEPHONY_SERVICE);
			imsi = telephonyManager.getSubscriberId();
		}
		if (!TextUtils.isEmpty(imsi)) {
			if (imsi.startsWith("46000") || imsi.startsWith("46002")) {
				return China_Mobile;
			} else if (imsi.startsWith("46001")) {
				return China_Unicom;
			} else if (imsi.startsWith("46003")) {
				return China_Telecom;
			}
		}
		return China_Unkown;
	}

}

4.判断当前手机的信号强度

4.1 wifi变化的广播接收者

public class WifiChangeBroadcastReceiver extends BroadcastReceiver{
	private Context mContext;
	private TextView myText8;  
	public WifiChangeBroadcastReceiver(TextView myText8) {
		this.myText8 = myText8;
	}

	@Override
    public void onReceive(Context context, Intent intent) {  
        mContext=context;  
        System.out.println("Wifi发生变化");  
        getWifiInfo();  
    }  
      
    private void getWifiInfo() {  
        WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE);  
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
        if (wifiInfo.getBSSID() != null) {  
            //wifi名称  
            String ssid = wifiInfo.getSSID();  
            //wifi信号强度  
            int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5);  
            //wifi速度  
            int speed = wifiInfo.getLinkSpeed();  
            //wifi速度单位  
            String units = WifiInfo.LINK_SPEED_UNITS;  
            myText8.setText("Wifi发生变化"+"\n"+"ssid="+ssid+",level="+level+",speed="+speed+",units="+units);
            System.out.println("ssid="+ssid+",level="+level+",speed="+speed+",units="+units);  
        }  
   }  
}

4.2 信号强度的各种信息

package zz.xinhaoqiangdu;

import java.util.List;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity { //TelephonyManager类的对象  
    private TelephonyManager Tel;  
  
    //MyPhoneStateListener类的对象,即设置一个监听器对象  
    private MyPhoneStateListener MyListener;

	private BroadcastReceiver receiver;

	private TextView myText8;

	private IntentFilter filter;  
  
    @Override  
    public void onCreate(Bundle savedInstanceState) {  
        //SignalStrength signalStrength;  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
       
        myText8 = (TextView)findViewById(R.id.myText8); 
        //初始化对象  
        MyListener = new MyPhoneStateListener();  
        //通过名字获得一个系统级服务  
        Tel = ( TelephonyManager )getSystemService(Context.TELEPHONY_SERVICE);  
        //设置监听器监听特定事件的状态  
        Tel.listen(MyListener ,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);  
        
        receiver = new WifiChangeBroadcastReceiver();
        filter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
		registerReceiver(receiver, filter);
        
        }  
    @Override  
    protected void onPause() {  
        super.onPause();  
        Tel.listen(MyListener, PhoneStateListener.LISTEN_NONE);  
    }  
    @Override  
    protected void onResume() {  
        super.onResume();  
        Tel.listen(MyListener,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);  
        registerReceiver(receiver, filter);
    }  
    //监听器类  
    private class MyPhoneStateListener extends PhoneStateListener{  
        /*得到信号的强度由每个tiome供应商,有更新*/  
        TextView myText = (TextView)findViewById(R.id.myText);  
        TextView myText1=(TextView)findViewById(R.id.myText1);  
        TextView myText2=(TextView)findViewById(R.id.myText2);  
        TextView myText3=(TextView)findViewById(R.id.myText3);  
        TextView myText4=(TextView)findViewById(R.id.myText4);  
        TextView myText5=(TextView)findViewById(R.id.myText5);  
        TextView myText6=(TextView)findViewById(R.id.myText6);  
        TextView myText7=(TextView)findViewById(R.id.myText7);  
        
        
        @Override  
        public void onSignalStrengthsChanged(SignalStrength signalStrength){  
            //调用超类的该方法,在网络信号变化时得到回答信号  
            super.onSignalStrengthsChanged(signalStrength);  
  
            //cinr:Carrier to Interference plus Noise Ratio(载波与干扰和噪声比)  
            //Toast.makeText(getApplicationContext(), "Go to Firstdroid!!! GSM Cinr = "+ String.valueOf(signalStrength.getGsmSignalStrength()), Toast.LENGTH_SHORT).show();  
            int level = signalStrength.getLevel();
            int cdmaDbm = signalStrength.getCdmaDbm();
            int CdmaEcio = signalStrength.getCdmaEcio();
            int EvdoDbm = signalStrength.getEvdoDbm();
            int EvdoEcio = signalStrength.getEvdoEcio();
            int EvdoSnr = signalStrength.getEvdoSnr();
            int GsmBitErrorRate = signalStrength.getGsmBitErrorRate();
            int GsmSignalStrength = signalStrength.getGsmSignalStrength();
            
            myText.setText("level = "+ level);  //信号格数
            myText1.setText("cdmaDbm  = "+ cdmaDbm);  
            myText2.setText("CdmaEcio = "+ CdmaEcio);  
            myText3.setText("EvdoDbm = "+ EvdoDbm);  
            myText4.setText("EvdoEcio = "+ EvdoEcio);  
            myText5.setText("EvdoSnr = "+ EvdoSnr);  
            myText6.setText("GsmBitErrorRate = "+ GsmBitErrorRate);  
            myText7.setText("GsmSignalStrength = "+ GsmSignalStrength);//信号强度  
        }  
    } 
    private class WifiChangeBroadcastReceiver extends BroadcastReceiver{
    	@Override
        public void onReceive(Context context, Intent intent) {  
            System.out.println("Wifi发生变化");  
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);  
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();  
            
            if (wifiInfo.getBSSID() != null) {  
                //wifi名称  
                final String ssid = wifiInfo.getSSID();  
                //wifi信号强度  
                final int level = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5);  
                //wifi速度  
                final int speed = wifiInfo.getLinkSpeed();  
                //wifi速度单位  
                final String units = WifiInfo.LINK_SPEED_UNITS;  
				myText8.setText("Wifi发生变化"+"\n"+"ssid="+ssid+",level="+level+",speed="+speed+",units="+units);
                System.out.println("ssid="+ssid+",level="+level+",speed="+speed+",units="+units);  
            }   
        }  
    }
    @Override
    	protected void onDestroy() {
    		unregisterReceiver(receiver);
    		super.onDestroy();
    	}
    
}

xml文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="zz.xinhaoqiangdu.MainActivity" >

    <TextView
        android:id="@+id/myText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText5"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText6"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText7"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <TextView
        android:id="@+id/myText8"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="50dip"
        android:text="监听wifi变化并获得当前信号强度" />

</LinearLayout>





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值