public class MainActivity extends Activity { private TextView tv; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) { int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0); switch (wifiState) { case WifiManager.WIFI_STATE_DISABLED: tv.setText("WIFI_STATE_DISABLED"); break; case WifiManager.WIFI_STATE_ENABLED: tv.setText("WIFI_STATE_ENABLED"); break; } } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tv = (TextView) findViewById(R.id.tv); } @Override protected void onResume() { super.onResume(); // 註冊廣播 IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); registerReceiver(receiver, filter); } }
WIFI_STATE_DISABLED : WIFI 不能使用,其值是: 1 。 WIFI_STATE_DISABLING : WIFI 正在關閉中,因爲 WIFI 關閉是須要這一個過程,這個狀態就表示 WIFI 正在關閉的過程當中, 其值是: 0 。 WIFI_STATE_ENABLED : WIFI 可使用,其值是: 3 。 WIFI_STATE_ENABLING : WIFI 正在開啓中,其道理同 WIFI_STATE_DISABLING ,其值是: 2 。 WIFI_STATE_UNKNOWN :未知網卡狀態,當手機或程序出現了一些錯誤引發 WIFI 不可用時會是這個狀態,其值是: 4 。
/** * 是否鏈接wifi * * @return */ public boolean isWifi() { ConnectivityManager connectivityManager = (ConnectivityManager) mActivity.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo(); if (activeNetInfo != null && activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) return true; return false; }