kdra kdra - 17 days ago 8
Android Question

Get notified only when data or wifi is disconnected

Hello guys i am building an application in which i want to notify the user only when the device looses connection whether its mobile data or wifi.

So far i have used this method:

private void setupReceiver() {
CheckNetworkStatusReceiver receiver = new CheckNetworkStatusReceiver();
registerReceiver(receiver, new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE"));
}


and my Receiver as such:

public class CheckNetworkStatusReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
if (intent != null){
Log.e("Action ",intent.getAction());
if(intent.getAction().equalsIgnoreCase("android.net.conn.CONNECTIVITY_CHANGE")) {
Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
}
}
}
}


and it works fine but the thing is that the toast also shows when it is connected to the network which is something i do not want. I only want the toast to show when its disconnects.

Any ideas?

Answer

before displaying toast check if connection available some thing like this

 if(!isNetworkAvailable()){
Toast.makeText(context, "Connection changed", Toast.LENGTH_SHORT).show();
 }




private boolean isNetworkAvailable() {
 ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
 NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
 return activeNetworkInfo != null; 
}