How check Internet-connection in Android? [duplicate] - java

This question already has answers here:
How do you check the internet connection in android? [duplicate]
(8 answers)
Closed 8 years ago.
What are the ways to check your Internet connection in Android.
And what is the difference between them?

Create method like below.
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
and call it wherever you want. Put it in IF - ELSE condition so you can check for connection.
Or if you want to call this method through out your project then you can create one static class like below.
public class ConnectivityDetector {
public static boolean isConnectingToInternet(Context context) {
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
and call it like below shown code in every class wherever you want.
if (ConnectivityDetector.isConnectingToInternet(Test.this)) {
// do your stuff
} else {
// Alert dialog that says, No Internet connection
}
Also make sure that you have the required permission to monitor the network state. You need to add this permission to your AndroidManifest.xml:
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Hope this will help you.

Related

How to choose the internet connection mode Android

I made an Android application that is used to exchange files with a pc.
The computer and the device are connected to the same network and everything worked very well.
But since I put a 4g sim card, the transfer is no longer done, does anyone know how to solve this problem?
There must be a way to force my application to use only ethernet connection?
Permissions:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
How I check connection:
public static Boolean isConnected(Context context) {
ConnectivityManager cm =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = null;
if (cm != null) {
activeNetwork = cm.getActiveNetworkInfo();
}
boolean isEthernet = false;
if (activeNetwork != null) {
isEthernet = activeNetwork.getType() == ConnectivityManager.TYPE_ETHERNET;
}
return activeNetwork != null &&
activeNetwork.isConnectedOrConnecting() && isEthernet;
}
Main function:
public void sendFilesInFolder(Boolean bool) {
if (isConnected(MainActivity.this)) {
ProgressBar progressBar;
if (bool) progressBar = mProgressBarD;
else progressBar = mProgressBarM;
fileSender = new FileSender(prefs.getString("ip_adress", null),
Integer.valueOf(prefs.getString("port_dest", null)),
bool, colisageBase, progressBar);
fileSender.execute();
} else {
Toast.makeText(MainActivity.this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
}
}

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

How to detect when user connects to wifi or mobile internet in android

I want to check for particular update when user each time connects to internet.I tried the following codes :
unfortunately app is getting stopped while checking for network
Broadcast receiver for checking internet connection in android app
Manifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<receiver android:name=".UpdateReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
Java
public class UpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE );
NetworkInfo activeNetInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isConnected = activeNetInfo != null && activeNetInfo.isConnectedOrConnecting();
if (isConnected)
Log.i("NET", "connecte" +isConnected);
else Log.i("NET", "not connecte" +isConnected);
}
}
My problem is these codes only receive only once , If the user disconnect wifi and reconnects the BroadcastReceiver unable to notify.Any help is appreciated .
Once I had implemented a check in my app, to see if there is any internet connection or not. You can have a look at this --
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context cont){
this.context = cont;
}
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null) {
for (int i = 0; i < info.length; i++) {
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
}
return false;
}
}
You can initialize an object of this class in your OnCreate method.
And finally call this class' method just before you upload files.
Boolean isInternetConnected = cd.isConnectingToInternet();
if (isInternetConnected)
{
//perform your job here.
}
EDITED::
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
Hope this helps.

Force close window in Async task execute [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Force close window, When Async task execute after connection is loss.
I'm tired using ConnectivityManager to check internet connection, because when device connect to wifi but no internet connection, ConnectivityManager showing is connected. can any body help me?
public boolean isConnected(){
boolean status=false;
ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
for (int i = 0; i<allNetworkInfo.length; i++){
if (allNetworkInfo[i].getState() == NetworkInfo.State.CONNECTED){
status = true;
}
}
return status;
}
you are almost done but need to check it also that network is connecting or connected.
public boolean isConnected(){
boolean status=false;
ConnectivityManager cManager=(ConnectivityManager) this.context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] allNetworkInfo = cManager.getAllNetworkInfo();
for (int i = 0; i<allNetworkInfo.length; i++){
if (allNetworkInfo[i].isConnectedOrConnecting()){
status = true;
}
}
return status;
}
I Hope it helps you...
You can try this code to see if it works:
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Try this code it works for me.
public static boolean isConnectedWithInternet(Context context) {
// return true;
boolean _isNetAvailable = false;
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (wifiNetwork != null) {
_isNetAvailable = wifiNetwork.isConnectedOrConnecting();
}
NetworkInfo mobileNetwork = cm
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (mobileNetwork != null) {
_isNetAvailable = mobileNetwork.isConnectedOrConnecting();
}
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
_isNetAvailable = activeNetwork.isConnectedOrConnecting();
}
// CGlobalVariables._isInternetOn = _isNetAvailable;
return _isNetAvailable;
}
You generally get an UnknownHostException when Internet is not reachable.
You should always check connected state before starting the request. But to handle connection loss during the process you can always catch UnknownHostException.

How to check programmatically if "use wireless networks" is enabled on Android?

I don't want to check if there is any connectivity over WIFI or 3G!
I just want to verify (and not change!) if the "Use wireless networks"-CheckBox is enabled (the one you can set in Settings > Location and security > My location > HERE)
Thanx
Code from RajaReddy will check if Wifi is enabled for network. If you want to know if Wifi is enabled for positioning then this should do (replace "context" with something useful)
ContentResolver cr = context.getContentResolver();
boolean wifiEnabled = Settings.Secure.isLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER);
example code for API Level < 8
private static boolean isWifiLocationEnabled (Context context) {
ContentResolver cr = context.getContentResolver();
String enabledProviders = Settings.Secure.getString(cr, Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!TextUtils.isEmpty(enabledProviders)) {
// not the fastest way to do that :)
String[] providersList = TextUtils.split(enabledProviders, ",");
for (String provider : providersList) {
if (LocationManager.NETWORK_PROVIDER.equals(provider)) {
return true;
}
}
}
return false;
}
use this code
public Boolean isNetAvailable(Context con) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) con.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo wifiInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiInfo.isConnected()) {
return true;
}
}catch(Exception e){
e.printStackTrace();
}
return false;
}
and following permissions are required for this
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>

Categories