Confirm Internet Data Connection Before Making Firestore Query
I have the following situation: The application has the option to like the posts of a user. And also has a Dislike option. It is working properly when it is on a wifi or mobile net
Solution 1:
A simple approch will be use the following method:
publicbooleanisInternetAvailable() {
Runtimeruntime= Runtime.getRuntime();
try {
Processprocess= runtime.exec("/system/bin/ping -c 1 8.8.8.8");
intexitValue= process.waitFor();
return (exitValue == 0);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
returnfalse;
}
Solution 2:
There are two ways to do this thing one is check at a instance and another is making a broadcast receiver
publicstaticbooleaninternetAvailable(Context context) {
ConnectivityManagerconnectivityManager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoactiveNetworkInfo=null;
if (connectivityManager != null) {
activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
}
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
And the other one is
publicclassNetworkChangeReceiverextendsBroadcastReceiver {
publicstaticfinalStringTAG="NetworkChangeReceiver";
publicstatic ConnectivityReceiverListener connectivityReceiverListener;
publicNetworkChangeReceiver() {
super();
}
@OverridepublicvoidonReceive(Context context, Intent intent) {
ConnectivityManagercm= (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfoactiveNetwork=null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
booleanisConnected= activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectivityReceiverListener != null) {
connectivityReceiverListener.onNetworkConnectionChanged(isConnected);
}
}
publicinterfaceConnectivityReceiverListener {
voidonNetworkConnectionChanged(boolean isConnected);
}
}
Happy Coding :)
Post a Comment for "Confirm Internet Data Connection Before Making Firestore Query"