获取android设备wifi连接状态

本文将介绍如何获取android设备wifi连接状态!


添加访问权限(AndroidManifest.xml文件里)

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


Java代码(MainActivity.java文件)

package com.example.androidtest;

import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		boolean bFlag = isWifiAvailable(this.getApplicationContext());
		if (bFlag) {
			Log.i("Wifi state - ", "connected");
		} else {
			Log.i("Wifi state - ", "not connected");
		}
		
	}
	
	/**
	 * 判断wifi连接状态
	 * 
	 * @param ctx
	 * @return
	 */
	public boolean isWifiAvailable(Context ctx) {
		ConnectivityManager conMan = (ConnectivityManager) ctx
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		State wifi = conMan.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
				.getState();
		if (State.CONNECTED == wifi) {
			return true;
		} else {
			return false;
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

}



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。