Reputation: 51
Can anyone help me how to show snackbar when WiFi or Mobile data not available on button press. Actually this button using for to send an email when user wants to send feedback form from my Android app.
My Requirement is: When user press button If any network available, then E-mail should send directly without showing Snackbar and snackbar should show when any network unavailable. I have been trying to solve my issue for last few days but no luck. My snackbar coding works all time like it showing everytime with and without network on button press on below API level 23 and not above.
Note: My code is working perfectly if don't give Snackbar coding. So I don't need email intent coding just I need network status coding with Snackbar.
If anyone provides correct solution it will help me a lot. Thank you in advance.
Upvotes: 1
Views: 1166
Reputation: 881
Use below function to check if internet is available or not
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
If it returns true, continue sending the email. Else display the snackbar.
You will need to add below permission to your manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Upvotes: 3
Reputation: 373
ConnectionDetect.class
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetect
{
private Context context;
public static boolean chechkagain;
public ConnectionDetect(Context context) {
this.context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifi = cm
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
NetworkInfo datac = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if ((wifi != null & datac != null)
&& (wifi.isConnected() | datac.isConnected())) {
chechkagain = true;
synchronized (context) {
context.notify();
}
} else {
chechkagain = false;
}
return chechkagain;
}
}
Now check internet available or not
if (connectionDetect.isConnectingToInternet()) {
//Send Email
} else {
Snackbar snackbar = Snackbar
.make(coordinatorLayout,
"Please check internet",
Snackbar.LENGTH_LONG);
snackbar.show();
}
coordinatorLayout is id of Coordinator Layout inside which we want to show snack bar
Upvotes: 2