好吧,这段代码对我来说很好,可以在使用 toast 更改时通知 WiFi 信号强度,所以
我的接收器是这样的
@Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = wifiDemo.wifi.getScanResults();
ScanResult bestSignal = null;
for (ScanResult result : results) {
if (bestSignal == null
|| WifiManager.compareSignalLevel(bestSignal.level, result.level) < 0)
bestSignal = result;
}
String message = String.format("%s networks found. %s is the strongest.",
results.size(), bestSignal.SSID);
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
Log.d("Debug", "onReceive() message: " + message);
}
这就是我在启动活动中注册 Receiver 并在 TextView 上获取 Wifi 信息的内容
public class WiFiDemo extends Activity {
WifiManager wifi;
BroadcastReceiver receiver;
TextView textStatus;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Setup UI
textStatus = (TextView) findViewById(R.id.textStatus);
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Get WiFi status
WifiInfo info = wifi.getConnectionInfo();
textStatus.append("\n\nWiFi Status: " + info.toString());
// List available networks
List<WifiConfiguration> configs = wifi.getConfiguredNetworks();
for (WifiConfiguration config : configs) {
textStatus.append("\n\n" + config.toString());
}
// Register Broadcast Receiver
if (receiver == null)
receiver = new WiFiScanReceiver(this);
registerReceiver(receiver, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Log.d(TAG, "onCreate()");
}
@Override
public void onStop() {
unregisterReceiver(receiver);
super.onStop();
}
}
我在XML 布局文件中的 TextView 上放置滚动视图
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ScrollView
android:id="@+id/ScrollView01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/textStatus"
android:text="WiFi Connections :" />
</ScrollView>
</LinearLayout>
最后我的清单看起来像这样
<uses-sdk android:minSdkVersion="10" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE">
</uses-permission>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE">
</uses-permission>
<activity android:name=".WiFiDemo" 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=".WiFiScanReceiver">
<intent-filter>
<action android:name="com.rdc" />
</intent-filter>
</receiver>
还有什么问题告诉我!!