我是Android初学者,我尝试编写一个程序,扫描所有可用的AP一次,然后将它们保存为字符串。
问题是我无法让程序只扫描一次,而是以下运行的输出是:
Scanning:
Done
Connected to AP
Connected to AP
Connected to AP
Connected to AP
Connected to AP
...
"扫描"调用ScanWifi()方法时,将打印到屏幕上。它只打印一次,因此表示该方法只运行一次。在此之后"完成"打印,表示该方法已返回。
然而,在那之后,有一个无限链"连接到AP",表明无线网络仍然在扫描。我试图在onReceive()函数的末尾添加一个return语句,但它没有任何区别。有什么想法吗?
WifiScan活动:
package com.example.wifi_scanner;
import android.support.v7.app.ActionBarActivity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;
public class WifiScan extends ActionBarActivity {
WifiManager wifi;
BroadcastReceiver receiver;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_wifi_scan);
textView = new TextView(this);
textView.setTextSize(10);
setContentView(textView);
}
@Override
protected void onStart() {
super.onStart();
scanWifi();
textView.append("\nDone");
return;
}
void scanWifi() {
final StringBuilder sb = new StringBuilder();
textView.setText("Scanning:");
// Setup receiver
registerReceiver(new BroadcastReceiver()
{
@Override
public void onReceive(Context c, Intent intent)
{
textView.append("\nConnected to AP");
sb.append(wifi.getScanResults().toString());
sb.append("\n");
return;
}
}, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
// Setup WiFi
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
// Start scan
wifi.startScan();
}
}
主要活动:
package com.example.wifi_scanner;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startScan(View view) {
Intent intent = new Intent(this, WifiScan.class);
startActivity(intent);
}
}
主要活动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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.wifi_scanner.MainActivity" >
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Scan Wifi"
android:onClick="startScan" />
</RelativeLayout>
答案 0 :(得分:1)
解决方案是控制布尔值的行为。您必须知道只要找到新的wifi,就会始终调用接收器。