android网络类型判断,状态变化监听

1.myReceiver.java 广播

public class MyReceiver extends BroadcastReceiver {
	@Override
	public void onReceive(Context context, Intent intent) {
		if (isNetworkConnected(context)) {
			int type = getConnectedType(context);
			switch (type) {
				case -1:
					Toast.makeText(context, "无有网络连接!请手动连接网络", Toast.LENGTH_SHORT)
							.show();
					break;
				case 0:
					Toast.makeText(context, "已经接入手机网络,请注意流量!", Toast.LENGTH_SHORT)
							.show();
					break;
				case 1:
					Toast.makeText(context, "WIFI网络", Toast.LENGTH_SHORT).show();
					break;
				case 2:
					Toast.makeText(context, "wap网络", Toast.LENGTH_SHORT).show();
					break;
				case 3:
					Toast.makeText(context, "net网络", Toast.LENGTH_SHORT).show();
					break;
				default:
					break;
			}
		} else {
			Toast.makeText(context, "无网络连接!请手动连接网络", Toast.LENGTH_SHORT).show();
		}
	}

	public boolean isNetworkConnected(Context context) {
		ConnectivityManager mConnectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
		if (mNetworkInfo != null) {
			return mNetworkInfo.isAvailable();
		}
		return false;
	}

	public static int getConnectedType(Context context) {
		if (context != null) {
			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
					.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo mNetworkInfo = mConnectivityManager
					.getActiveNetworkInfo();
			if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
				return mNetworkInfo.getType();
			}
		}
		return -1;
	}
}

2.在入口activity.java注册广播

public class MainActivity extends Activity {
    TextView textView;
    Button button;
    IntentFilter intentFilter;
    MyReceiver myReceiver = new MyReceiver();

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

    public void initView() {

        textView = (TextView) findViewById(R.id.tv);
        button = (Button) findViewById(R.id.btn);


        intentFilter = new IntentFilter();
        intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);   
        //为BroadcastReceiver指定action,使之用于接收同action的广播
        //registerReceiver(myReceiver, intentFilter);
        Intent service = new Intent(this, MyReceiver.class);
        startService(service);


        button.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (isNetworkConnected(getApplicationContext())) {
                    // -1:没有网络 0:手机网络 1:WIFI网络 2:wap网络 3:net网络
                    int type = getConnectedType(getApplicationContext());
                    switch (type) {
                        case -1:
                            textView.setText("无网络接入" + type);
                            Toast.makeText(getApplicationContext(),
                                    "无有网络连接!请手动连接网络", Toast.LENGTH_SHORT).show();

                            break;
                        case 0:
                            textView.setText("已经接入手机网络,请注意流量!" + type);
                            Toast.makeText(getApplicationContext(),
                                    "已经接入手机网络,请注意流量!", Toast.LENGTH_SHORT).show();
                            break;
                        case 1:
                            textView.setText("WIFI网络" + type);
                            Toast.makeText(getApplicationContext(), "WIFI网络",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case 2:
                            textView.setText("wap网络" + type);
                            Toast.makeText(getApplicationContext(), "wap网络",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        case 3:
                            textView.setText("net网络" + type);
                            Toast.makeText(getApplicationContext(), "net网络",
                                    Toast.LENGTH_SHORT).show();
                            break;
                        default:
                            break;
                    }
                } else {
                    textView.setText("无网络接入");
                    Toast.makeText(getApplicationContext(), "无有网络连接!请手动连接网络",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onStop() {
        super.onStart();
        /**
         * 卸载广播
         */
        unregisterReceiver(myReceiver);
    }

    /**
     * 判断有无网络连接
     *
     * @param context
     * @return
     */
    public boolean isNetworkConnected(Context context) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (mNetworkInfo != null) {
            return mNetworkInfo.isAvailable();
        }
        return false;
    }
//
//	public boolean isMobileConnected(Context context) {
//		if (context != null) {
//			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
//					.getSystemService(Context.CONNECTIVITY_SERVICE);
//			NetworkInfo mMoBileNetworkInfo = mConnectivityManager
//					.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//			if (mMoBileNetworkInfo != null) {
//				return mMoBileNetworkInfo.isAvailable();
//			}
//		}
//		return false;
//	}
//
//	public boolean isWifiConnected(Context context) {
//		if (context != null) {
//			ConnectivityManager mConnectivityManager = (ConnectivityManager) context
//					.getSystemService(Context.CONNECTIVITY_SERVICE);
//			NetworkInfo mWiFiNetworkInfo = mConnectivityManager
//					.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
//			if (mWiFiNetworkInfo != null) {
//				return mWiFiNetworkInfo.isAvailable();
//			}
//		}
//		return false;
//	}

    public static int getConnectedType(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager
                    .getActiveNetworkInfo();
            if (mNetworkInfo != null && mNetworkInfo.isAvailable()) {
                return mNetworkInfo.getType();
            }
        }
        return -1;
    }

}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.zdemo.network"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.zdemo.network.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <!-- 注册网络判断的广播 start -->
        <receiver android:name="util.MyReceiver" >
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />

                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>
        <!-- 注册网络判断的广播 end -->
    </application>

</manifest>

activity_main.xml

<RelativeLayout 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"
    tools:context=".MainActivity" >
<Button 
    android:id="@+id/btn"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="点击监测网络状态"/>
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_below="@id/btn"/>

</RelativeLayout>

把代码拷贝运行就OK了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android中可以通过使用TelephonyManager类来监听基站网络状态。 首先,需要在AndroidManifest.xml文件中添加以下权限: ``` <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ``` 然后,在需要监听基站网络状态的地方,可以创建一个TelephonyManager对象,并注册一个PhoneStateListener来监听网络状态变化。示例如下: ``` TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); PhoneStateListener phoneStateListener = new PhoneStateListener() { @Override public void onSignalStrengthsChanged(SignalStrength signalStrength) { super.onSignalStrengthsChanged(signalStrength); // 获取基站信号强度等信息 int gsmSignalStrength = signalStrength.getGsmSignalStrength(); int cdmaDbm = signalStrength.getCdmaDbm(); int evdoDbm = signalStrength.getEvdoDbm(); // 进行相应的处理逻辑 // ... } @Override public void onDataConnectionStateChanged(int state, int networkType) { super.onDataConnectionStateChanged(state, networkType); // 获取网络连接状态网络类型 if (state == TelephonyManager.DATA_CONNECTED) { // 网络已连接 } else { // 网络未连接 } // 进行相应的处理逻辑 // ... } }; telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_SIGNAL_STRENGTHS | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE); ``` 通过以上代码,就可以监听到基站网络状态变化,可以在相应的回调方法中进行相应的处理逻辑,例如获取基站信号强度等信息,判断网络连接状态等。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值