onReceive of BroadcastReceiver shows alert 2 times in android -


i implementing internet connectivity lost in application using broadcastreceiver.the code working fine alert shown on internet connection or disconnection showing twice.i want show alert or toast once @ time.below code of broadcastreceiver

public void onreceive(context context, intent intent) {              if (intent.getaction().equals("android.net.conn.connectivity_change")) {                 connectivitymanager cm =                         (connectivitymanager) context.getsystemservice(context.connectivity_service);                 //networkinfo activenetwork = cm.getactivenetworkinfo();                  if (cm.getnetworkinfo(connectivitymanager.type_mobile).getstate() == networkinfo.state.connected                         || cm.getnetworkinfo(connectivitymanager.type_wifi).getstate() == networkinfo.state.connected) {                      // notify user online                     toast.maketext(context.getapplicationcontext(), "connected", toast.length_long).show();                  } else if (cm.getnetworkinfo(connectivitymanager.type_mobile).getstate() == networkinfo.state.disconnected                         || cm.getnetworkinfo(connectivitymanager.type_wifi).getstate() == networkinfo.state.disconnected) {                     constants.alert("please check internet connection", context);                      // notify user not online                 } 

receiving multiple broadcast device specific problem. phones send 1 broadcast while other send 2 or 3. there work around:

assuming disconnect message when wifi disconnected, guess first 1 correct 1 , other 2 echoes reason.

to know message has been called, have static boolean gets toggled between connect , disconnect , call sub-routines when receive connection , boolean true. like:

public class connectionchangereceiver extends broadcastreceiver {  private static boolean firstconnect = true;  @override public void onreceive(context context, intent intent) {     final connectivitymanager connectivitymanager = (connectivitymanager) context.getsystemservice(context.connectivity_service);     final networkinfo activenetinfo = connectivitymanager.getactivenetworkinfo();     if (activenetinfo != null) {         if(firstconnect) {              // subroutines here             firstconnect = false;         }     }     else {         firstconnect= true;     } } } 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -