新しいタイマーとタスクを作成せずにこれを行う方法はありますか? 私のコードは、基本的に 10 秒ごとに Wi-Fi 信号をスキャンします。スキャンが確実に新しい結果を返すようにするために、別のサポート クラスを使用しました。これにも明らかなエラーがないことを誰かが確認できますか?
//Inside Button to start scanning
final int DELAY = 10000;
final Handler handler = new Handler();
chkScan.setOnClickListener(new View.OnClickListener() {
final Handler handler = new Handler();
ReceiverWifi = new WifiReceiver();
WIFI_Manager = new wifiScanner();
registerReceiver(receiverWifi, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
final Timer timer = new Timer();
final TimerTask task = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
mainWifi.startScan();
if ((WIFI_Manager.resultsAvailable())) {
processResults();
}
// to ensure results come from latest scan
// say there are no new results as of now
WIFI_Manager.waitForNextScan();
}
}
);
timer.schedule(task, 0, DELAY);
}
}
});
}
public void processResults() {
results = mainWifi.getScanResults();
WIFI_Manager.pause() //stop getting wifi results
//continue to process here
//
//
//I wish to put a button here, but and wait for user input before continuing
//but scans continue..
chkLabel.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
}
//more code
// ...
WIFI_Manager.resume();
}
class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context c, Intent intent) {
WIFI_Manager.getNewResults();
}
}
public class wifiScanner {
public wifiScanner() {
Pause = false;
new_results = false;
}
public boolean resultsAvailable() {
return new_results;
}
public void waitForNextScan() {
new_results = false;
}
public void getNewResults() {
new_results = true;
}
public boolean onPause() {
return Pause;
}
public void pause() {
unregisterReceiver(receiverWifi);
Pause = true;
}
public void resume() {
registerReceiver(receiverWifi, new IntentFilter(
WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));
Pause = false;
}
// pause: false- access to scan results are allowed
// pause: true- cannot access scan results
private boolean Pause;
// new_results: false- no new WIFI_resuls
// new_results: true - there are new results to be processed
private boolean new_results;
}