Realtime Network Check - Android - java

I have an app and in that, I want to check the real-time network of the mobile phone.
This is my java code:
This is only some of the full java file.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
if (checkNetwork() == false) {
Toast noNetwork = Toast.makeText(getApplicationContext(), "Sync is paused, due to no
internet...", Toast.LENGTH_LONG);
noNetwork.show();
} else if (checkNetwork() == true) {
Toast yesNetwork = Toast.makeText(getApplicationContext(), "Sync is turned on...",
Toast.LENGTH_LONG);
yesNetwork.show();
}
// This code we will add later - bottomNavigation.getMenu().removeItem(R.id.navigation_notes);
}
private boolean checkNetwork() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
If I open my app and navigate to this page, it shows the internet is there toast, but at the same time when I turn off mobile data, the other toast which shows internet is not there is not shown. I think the above code is not real-time or there is a problem with the toast, I don't know.
I want to know if there are ways in which I could make the above code real-time. Thanks in advance.

Register a NetworkCallback using registerNetworkCallback() method. Example code is given here.

Related

How to use a custom No Internet Connection Available layout when user is offline?

I have been trying to use a custom Image that is to be shown to a user when he is offline and when the user clicks on the image, the activity should be reloaded.
P.s I am using Blogger API
first add this permission to manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
thin in your activty
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
and use like this
if(isNetworkAvailable()){
//internt connect
}else{
// no network
//you can show image here by adding layout and set visibility gone and when no connection set visible
}
You can use Custom Dialog of full Screen to check for internet. So, you can write,
if(isNetworkAvailable()){
//Your Logic for Internet Connection
}else {
val noInternetDialog = Dialog(this, android.R.style.Theme)
noInternetDialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
noInternetDialog.setContentView(R.layout.no_internet_layout)
val window = noInternetDialog.window
window.setLayout(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
// What ever you have widget, can use them here.
//for example
val button_try_again = noInternetDialog.findViewById(R.id.buttonId)
val image_to_display = noInternetDialog.findViewById(R.id.imageId)
// listeners for image
noInternetDialog.show
}
isNetworkAvaibale() is,
fun isNetworkAvailable(): Boolean {
val connectivityManager = ApplicationInit.getAppContext()
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val activeNetworkInfo = connectivityManager.activeNetworkInfo
return activeNetworkInfo != null && activeNetworkInfo.isConnected
}
PS : Do not forget to add Internet Permissions

Android Firebase check connection status?

I have an App with the Firebase Realtime Database. This app should display a ProgressBar if it isn't connected. How can I do that? I tried it with ".info/connected", but the results seem pretty random. I need to check the connection to the online database, not the offline database. (basically, i want to disable offline capabilities, and show the user if they are offline)
var firebaseRef = new Firebase('http://INSTANCE.firebaseio.com');
firebaseRef.child('.info/connected').on('value', function(connectedSnap) {
if (connectedSnap.val() === true)
{
/* we're connected! */
}
else {
/* Give a custom Toast / Alert dialogue and exit the application */
}
});
You can also add this check
public static boolean isNetworkAvailable(Context con) {
try {
ConnectivityManager cm = (ConnectivityManager) con
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Then check this in your Activity/Fragment
if (isNetworkAvailable)
{
//Do you task
}
else{
/*No internet so Give a custom Toast / Alert dialogue and exit the application */
}
Refer this link for more information
Some nicer check of network connection in kotlin:
val Context.isNetworkConnected
get() = (getSystemService(ContextWrapper.CONNECTIVITY_SERVICE) as ConnectivityManager)
.activeNetworkInfo?.isConnected ?: false

I want to refresh my fragment UI through broadcast receiver

I have a Main Activity, which holds 1 fragment. The fragment is responsible for drawing the UI, running an Async task, etc. All of this requires an internet connection. Now when I first launch my app I check whether there is an internet connection or not through a method:
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return (activeNetworkInfo != null && activeNetworkInfo.isConnectedOrConnecting());
}
If there is no network connection, the activity starts the fragment, but I've made it so that without an internet connection nothing shows (since there is nothing to show because I am downloading content from an online database).
I want to implement a broadcast receiver, which would restart the fragment somehow, when there is an internet connection available. So far I have a broadcast receiver as an Inner class in my Main activity:
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, final Intent intent) {
if (intent.getExtras() != null) {
final ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo ni = connectivityManager.getActiveNetworkInfo();
if (ni != null && ni.isConnectedOrConnecting()) {
Toast.makeText(context, "internet ++", Toast.LENGTH_LONG).show();
//this is where the fragment needs to be somehow reinstantiated
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
Toast.makeText(context, "internet --", Toast.LENGTH_LONG).show();
}
}
}
};
I've tried to make the broadcast receiver an outer class, but then I cannot do anything to the fragment.. When it is an Inner class, nothing happens with the code from the broadcast receiver. I've reviewed a lot of similar questions, but nothing seems to work from me.
So the question at hand would be: How do I refresh a fragment inside an activity, when the internet connection becomes available while the app is running?
Your implementation is just wrong. You should start your fragment and request through the network, and meanwhile show ProgressBar or something else to the user. If Internet is not available, in any way, you get the error then show user the problem. On the other hand, if you get the response successfully, just set your data to your view. BTW, your method for finding availability of network is not guaranteed that "Internet" is available.

Notification every time wifi is disconnected [duplicate]

This question already has an answer here:
Notification every time wifi disconnects
(1 answer)
Closed 9 years ago.
I need my application to give a notification whenever WiFi goes offline.
I got it to give a notification every time the WiFi connection changes. But I need it to only give a notification when it goes offline.
Also it gives a notification on start-up (of the application).
My question is, how do I alter the code to only give a notification when WiFi goes offline? Now it gives a notification when it goes offline, online and on start-up.
The code:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.registerReceiver(this.mConnReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
setContentView(R.layout.activity_main);
}
private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
if(currentNetworkInfo.isConnected()){
}
else{showNotification();}
}
};
use this line in onReceive() of BroadCastReceiver
if(!isNetworkConnectionAvailable(ctx)){
Toast.makeText(ctx, "Network Connection Available ", Toast.LENGTH_LONG).show();
}
the code for isNetworkConnectionAvailable() is
public static boolean isNetworkConnectionAvailable(Context context)
{
boolean isNetworkConnectionAvailable = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService("connectivity");
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null)
{
isNetworkConnectionAvailable = activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED;
}
return isNetworkConnectionAvailable;
}
comment me about result
Use this to check connectivity InetAddress.isReachable, the method returns true if you have connectivity else false

Internet Availability on Android

My problem is that my application have around 12-13 screen, and all of that uses internet to parse data. So if my application lost an internet connection, it should alert user with "no internet available" message.
Is there any built-in service or methods that check internet avilability in background and alert user if internet is not available?
You can use this function:
protected boolean isNetworkConnected() {
Context ctx = this;
ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo network = cm.getActiveNetworkInfo();
if (network != null) {
return network.isAvailable();
}
return false;
}

Categories