问题
So someone asked me to write an app for him that logs starts and stop, bssid, local ip, ssid and start/stop time when he connects to a WiFi access point.
I did this by:
public void onReceive(Context context, Intent intent) {
ConnectivityManager connManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
TelephonyManager telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
if (mWifi.isConnected()) {
WifiManager wifiManager = (WifiManager) context
.getSystemService(Context.WIFI_SERVICE);
android.net.wifi.WifiInfo wifiInfo = wifiManager
.getConnectionInfo();
SSID = wifiInfo.getSSID();
BSSID = wifiInfo.getBSSID();
localIp = getLocalIpAddress();
Log.d("WIFI SSID",SSID);
Log.d("WIFI MAC", BSSID);
Log.d("WIFI IP", localIp);
this.startDate = c.getTime();
}
while(mWifi.isConnected()){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.stopDate = c.getTime();
db.insertWifiInfo(SSID, BSSID,telephonyManager.getDeviceId(), localIp, startDate, stopDate);
}
This method get's called by this intent filter:
<intent-filter>
<action android:name="android.net.wifi.WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION" >
</action>
</intent-filter>
However is this the best way to be able to log start and stop time? Is wait() inefficient ?
回答1:
Is wait() inefficient ?
Yes this totally not wrong.
Read about BroadcastReceiver in android. Here is what you need to do:
protected void onResume()
{
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
registerReceiver(myReceiver, intentFilter);
}
private BroadcastReceiver myReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context context, Intent intent) {
String str = intent.getAction();
displayMessage("In myReceiver, action = " + str);
Log.d("Settings", "Received action: " + str);
if (str.equals("android.net.wifi.WIFI_STATE_CHANGED"))
displayMessage("wifi changed...");
}};
回答2:
Why bother doing that while(connected){wait}
thing? I would think you'd get another broadcast of SUPPLICANT_CONNECTION_CHANGE_ACTION:
Broadcast intent action indicating that a connection to the supplicant has been established (and it is now possible to perform Wi-Fi operations) or the connection to the supplicant has been lost. One extra provides the connection state as a boolean, where true means CONNECTED.
You could just check that extra every time to see whether you started or stopped the connection. That way your app doesn't even have to be running between start and stop.
来源:https://stackoverflow.com/questions/9640880/android-waiting-for-an-action