Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Receive 3 Broadcasts When the Network Switched from GPRS to Wifi

Tags:

android

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.

like image 729
happyz90 Avatar asked Nov 13 '22 19:11

happyz90


1 Answers

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;
like image 172
Girish Nair Avatar answered Nov 15 '22 12:11

Girish Nair