When the network switched from GPRS to Wifi, I received 3 times of Broadcast of android.net.conn.CONNECTIVITY_CHANGE.
In onReceive(), I use the code below to judge whether Wifi connected. But I also received 3 times of message of "Wifi Connected", and doSomething() was called 3 times.
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiInfo.isConnected()) {
Log.v(Constant.APP_NAME, "Wifi Connected.");
doSomething();
}
I want to receive only ONE message of "Wifi Connected", and call doSomething() only ONCE. How should I do?
Thank you. And sorry for my poor English.
Create a boolean flag value that checks for the messsage make it static if you want it to be accessable from some wehere else Eg
public static boolean flagConnected = false;
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiInfo.isConnected() && flagConnected == false) {
flagConnected = true;
Log.v(Constant.APP_NAME, "Wifi Connected.");
doSomething();
}
After doSomething(); you can change the value of the flag to false again
ClassName.flagConnected = false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With