Android監聽WIFI網絡的變化并且獲得當前信號強度
MainActivity如下:
WifiChangeBroadcastReceiver如下:
package cc.testwifi; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class WifiChangeBroadcastReceiver extends BroadcastReceiver { private Context mContext; @Override public void onReceive(Context context, Intent intent) { mContext=context; System.out.println("Wifi發生變化"); getWifiInfo(); } private void getWifiInfo() { WifiManager wifiManager = (WifiManager) mContext.getSystemService(mContext.WIFI_SERVICE); WifiInfo wifiInfo = wifiManager.getConnectionInfo(); if (wifiInfo.getBSSID() != null) { //wifi名稱 String ssid = wifiInfo.getSSID(); //wifi信號強度 int signalLevel = WifiManager.calculateSignalLevel(wifiInfo.getRssi(), 5); //wifi速度 int speed = wifiInfo.getLinkSpeed(); //wifi速度單位 String units = WifiInfo.LINK_SPEED_UNITS; System.out.println("ssid="+ssid+",signalLevel="+signalLevel+",speed="+speed+",units="+units); } } }
AndroidManifest.xml如下:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="cc.testwifi" android:versionCode="1" android:versionName="1.0" > <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="10" /> <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="cc.testwifi.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> <receiver android:name="cc.testwifi.WifiChangeBroadcastReceiver"> <intent-filter > <action android:name="android.net.wifi.RSSI_CHANGED" /> </intent-filter> </receiver> </application> </manifest>
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" > <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="監聽wifi變化并獲得當前信號強度" android:layout_centerHorizontal="true" android:layout_marginTop="50dip" /> </RelativeLayout>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!