【Android】利用广播BroadCast监听网络的变化


package com.app.test02;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.widget.Toast;
/**
 * Android  利用广播BroadCast监听网络的变化
 * @author 402-9
 *
 */
public class BroadCastDemo extends BroadcastReceiver{
	State wifiState = null;
	State mobileState = null;
	public static final String ACTION = "android.net.conn.CONNECTIVITY_CHANGE";
	@Override
	public void onReceive(Context context, Intent intent) {
		// TODO Auto-generated method stub
		if (ACTION.equals(intent.getAction())) {
			//获取手机的连接服务管理器,这里是连接管理器类
			ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);	
			wifiState = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();	
			mobileState = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
	
			Intent intent2 = new Intent(context , BroadCastActivity2_SMS.class);
			if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED == mobileState) {
				context.startService(intent2);
				Toast.makeText(context, "手机网络连接成功!", Toast.LENGTH_SHORT).show();
			} else if (wifiState != null && mobileState != null && State.CONNECTED == wifiState && State.CONNECTED != mobileState) {
				context.startService(intent2);
				Toast.makeText(context, "无线网络连接成功!", Toast.LENGTH_SHORT).show();
			} else if (wifiState != null && mobileState != null && State.CONNECTED != wifiState && State.CONNECTED != mobileState) {
				context.startService(intent2);
				Toast.makeText(context, "手机没有任何网络...", Toast.LENGTH_SHORT).show();
			}
		}
	}

}


增加权限

        <receiver android:name=".BroadCastDemo">
            <intent-filter >
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
            </intent-filter>
        </receiver>

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

效果图

【Android】利用广播BroadCast监听网络的变化_第1张图片


【Android】利用广播BroadCast监听网络的变化_第2张图片

你可能感兴趣的:(android,网络,监听,Broadcast,广播)