Android Firebase check connection status? - java

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

Related

Realtime Network Check - Android

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.

How do I perform network operation programmatically on WiFi and cellular data separately when both are connected in Android Studio?

This is the code that is used to connect to a screen with wifi on address 192.168.22.1.
It is working fine when connecting with mobile data turned off, but doesn't work if mobile data is on:
public void onConnectClicked(View view){
Y2Screen screen = new Y2Screen("http://192.168.22.1");
final TextView message=findViewById(R.id.mess);
try {
message.setText("Connecting....");
if (!screen.login("guest", "guest")) {
message.setText("Connection Failed");
} else {
message.setText("Done Loging.");
//VideoArea va = new VideoArea(0, 0, screen.getWidth(), screen.getHeight());
PicArea pa=new PicArea(0, 0, screen.getWidth(), screen.getHeight());
File dir = Environment.getExternalStorageDirectory();
String path = dir.getAbsolutePath();
//va.addVideo(path+"/glomo/image.jpeg", 100);
pa.addPage(path+"/glomo/test3.png","PNG");
ProgramPlayFile prog = new ProgramPlayFile(1);
prog.getAreas().add(pa);
String listId = screen.writePlaylist(new ProgramPlayFile[]{prog});
screen.play(listId);
}
} catch (Y2Exception e) {
e.printStackTrace();
}
}
Probably is because 192.168.22.1 is a local address, so it is only accessible from local network (wifi, ...). If you are using mobile connection data you are on the public internet so you will need to NAT that local address to a public address port.
You can detect the type of connection using:
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
More info at Detect network connection type on Android and about NAT issue: Get the NAT translated IP and port of some local port and How to expose my localhost to the WWW? (port forwarding?)
If you have both connections active loop all the networks from connectivityManager.getAllNetworks() and choose one with connectivityManager.bindProcessToNetwork(network);
for (Network network : connectivityManager.getAllNetworks()) {
NetworkInfo networkInfo = connectivityManager.getNetworkInfo(network);
if (networkInfo.getType() == ConnectivityManager.TYPE_ETHERNET || networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
connectivityManager.bindProcessToNetwork(network);
break;
}
}
See Use multiple network interfaces in an app
I found out a solution for that and its working, we just need to change the network channel to transport through wifi instead of mobile internet.
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
final ConnectivityManager manager = (ConnectivityManager) MainActivity.this
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest.Builder builder;
builder = new NetworkRequest.Builder();
//set the transport type do WIFI
builder.addTransportType(NetworkCapabilities.TRANSPORT_WIFI);
manager.requestNetwork(builder.build(), new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
manager.bindProcessToNetwork(network);
} else {
//This method was deprecated in API level 23
ConnectivityManager.setProcessDefaultNetwork(network);
}
try {
} catch (Exception e) {
e.printStackTrace();
}
manager.unregisterNetworkCallback(this);
}
});
}

Check if connected to specific wifi on app start

When my app starts I want to check if the device is connected to a specific wifi, my current code looks like this
private boolean haveNetwork() {
boolean have_WIFI = false;
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
for (NetworkInfo info:networkInfos) {
if (info.getTypeName().equalsIgnoreCase("WIFI" )) {
if (info.isConnected())
have_WIFI = true;
}
}
return have_WIFI;
}
But it only checks if the device has any WIFI connection at all. How would I modify it to check for a specific WIFI SSID e.g. "Home"?

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

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