我的Service类中创建了一个broadcastreceiver。 它被设置为对此操作做出反应:WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
所以基本上每次我都做wifi.startScan()的方法调用; ,结果变得可用,广播接收者的onReceive方法做了它的事情。
我的问题是我需要处理这些扫描结果,并且在广播接收器中做这么多可能不是很好的做法。我想在我的服务类中进行所有计算,但我需要以某种方式访问ScanResults。
对此有何帮助?因为它非常需要。
这是我的代码的简化版本,传达了我的广播接收者的目的:
我的服务类的片段:
IntentFilter i = new IntentFilter();
i.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION); //reacts to the scan results being available
registerReceiver(mybroadcast,i);
wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(!wifi.isWifiEnabled()){ // if wifi is not enabled
toast = Toast.makeText(getApplicationContext(), "Wifi is off. Please turn it on.", Toast.LENGTH_LONG);
toast.show();
//wifi.setWifiEnabled(true);
//startActivity(backIntent);
}
else
{
wifi.startScan(); //what the receiver is going to react to
}
我的收件人代码:
private final BroadcastReceiver mybroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
//gets the scan results
wifi = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE);
List<ScanResult> scans = wifi.getScanResults();
// do some work here...
}
}
答案 0 :(得分:0)
您可以尝试为ex:
添加处理程序private final Handler handler = new Handler() {
public void handleMessage(Message msg) {
String aResponse = msg.getData().getString("message");
if ((null != aResponse)) {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Server Response: " + aResponse, Toast.LENGTH_SHORT)
.show();
} else {
// ALERT MESSAGE
Toast.makeText(getBaseContext(),
"Not Got Response From Server.", Toast.LENGTH_SHORT)
.show();
}
}
};
并在您的BroadcastReceiver的OnReceive中向其发送消息:
Message msgObj = handler.obtainMessage();
Bundle b = new Bundle();
b.putString("message", msg);
msgObj.setData(b);
handler.sendMessage(msgObj);