本文将介绍如何获取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; } }
时间: 2024-09-29 15:35:30