我无法弄清楚我写错了什么。这似乎是一个非常简单的案例,但我无法做到这一点。
1。 registerReceiver返回null,这有关系吗? 2。接收者onReceive没有被调用 - 这是与registerReceiver相关联的 给予空。
以下是我的活动中的代码
WifiManager mainWifiObj;
WifiScanReceiver wifiReceiver;
String wifis[];
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainWifiObj = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiReceiver = new WifiScanReceiver();
final Button button = (Button) findViewById(R.id.nextButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
mainWifiObj.startScan();
}
});
}
protected void onStop() {
unregisterReceiver(wifiReceiver);
super.onStop();
}
protected void onStart() {
registerReceiver(wifiReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
//registerReceiver returning null
super.onStart();
}
class WifiScanReceiver extends BroadcastReceiver {
@SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
List<ScanResult> wifiScanList = mainWifiObj.getScanResults();
wifis = new String[wifiScanList.size()];
Log.v(this.getClass().getName(), "wifiScanList.size() : "
+ wifiScanList.size());
for (int i = 0; i < wifiScanList.size(); i++) {
wifis[i] = ((wifiScanList.get(i)).toString());
Log.v(this.getClass().getName(), wifiScanList.get(i).SSID);
}
}
}
这是我的清单
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.i2e1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.CHANGE_WIFI_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=".FirstStateActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
我参考了http://www.tutorialspoint.com/android/android_wi_fi.htm 并尝试重现类似的代码,但它有效。
我在Android的Android模拟器中运行它。