Connection status - how to call method from another class - java

I wrote application which have to check status if internet connection and I would like to call this method in another class, but I don't know how should I do this.
Here is the code responsible for checking internet connection:
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
and broadcast class:
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
I would like to check in another class, or at the moment there is no connection (getConnectivityStatus return TYPE_NOT_CONNECTED) and execute some code like this:
if (connection is missing - i don't know what should i put in this place) {
// other code
}
else {
}
Can you help me?

Not sure what your problem is...
if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == NetworkUtil.TYPE_NOT_CONNECTED) {
}else {
}
Hope it helps

if (NetworkUtil.getConnectivityStatus(getApplicationContext()) == NetworkUtil.TYPE_NOT_CONNECTED) {
//NOT CONNECTED!
}else {
//CONNECTED!
}
you can also change your method to retrieve a boolean value:
public static boolean getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return true;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return true;
}
return false;
}
and your code will be like:
if (NetworkUtil.getConnectivityStatus(getApplicationContext())) {
//CONNECTED!
}else {
//NOT CONNECTED!
}
Note:
If you are inside a fragment you can call your method as:
NetworkUtil.getConnectivityStatus(getActivity().getApplicationContext())

here what I made:
First i register my receiver in my activity :
registerReceiver(
new NetworkChangeReceiver(),
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION)
);
here is my Receiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
private static final String TAG = "NetworkStateReceiver";
#Override
public void onReceive(Context context, Intent intent) {
Log.v(TAG, "[status]: " + NetworkUtils.getConnectivityStatus(context));
}
}
and finally my NetworkUtils is as simple as this :
public enum NetworkStatus{
NETWORK_STATUS_NOT_CONNECTED,
NETWORK_STATUS_WIFI,
NETWORK_STATUS_MOBILE
}
public static NetworkStatus getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return NetworkStatus.NETWORK_STATUS_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return NetworkStatus.NETWORK_STATUS_MOBILE;
}
return NetworkStatus.NETWORK_STATUS_NOT_CONNECTED;
}
}

Related

How can I check internet connection in Android Q?

Before Android Q all you had to do is use the NetworkUtils class. But this class was deprecated in API 29.
I've been searching for an alternative, and I couldn't seem to find one.
So, how can I check the internet connection in Android Q?
Use this code snippet.
#IntRange(from = 0, to = 3)
public static int getConnectionType(Context context) {
int result = 0; // Returns connection type. 0: none; 1: mobile data; 2: wifi
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = 2;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = 1;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_VPN)) {
result = 3;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = 2;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = 1;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_VPN) {
result = 3;
}
}
}
}
return result;
}
Add the below permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
If you are looking for a simple code, you can use this:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return cm.getActiveNetwork() != null && cm.getNetworkCapabilities(cm.getActiveNetwork()) != null;
} else {
return cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
}
The ConnectivityManager only checks whether the smartphone could theoretically establish an Internet connection. Whether an Internet connection actually exists, e.g. if the network quality is very poor, can only be determined with a ping or a web address.
Just use this code and call isInternatAvailable(context).
private static final String CMD_PING_GOOGLE = "ping -w -c 1 google.com";
public static boolean isInternetAvailable(#NonNull Context context) {
return isConnected(context) && checkInternetPingGoogle();
}
public static boolean isConnected(#NonNull Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
} else {
return false;
}
}
public static boolean checkInternetPingGoogle(){
try {
int a = Runtime.getRuntime().exec(CMD_PING_GOOGLE).waitFor();
return a == 0x0;
} catch (IOException ioE){
EMaxLogger.onException(TAG, ioE);
} catch (InterruptedException iE){
EMaxLogger.onException(TAG, iE);
}
return false;
}

How to use Connectivity manager.NetworkCallback to get network type

In my project I want to show the type of connection that is used.
For example when the user enables wifi and opens the app
The toast with WiFi enabled is shown if used mobile data then another toast should be shown.
I used the following code to show the type but I found that TYPE_WIFI & TYPE_MOBILE is deprecated and suggests to use the ConnectivityManager.NetworkCallback();. So I'm confused how to use it
Just help me know how to do that
Here is my code snippet
public void CheckConnection(){
ConnectivityManager manager = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = manager.getActiveNetworkInfo();
if(null!=activeNetwork){
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI){
Toast.makeText(this, "Connected with Wi-Fi", Toast.LENGTH_SHORT).show();
}
else if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE){
Toast.makeText(this, "Connected with Cellular Data", Toast.LENGTH_SHORT).show();
}
}
else {
Toast.makeText(this,"No Internet connection Detected",Toast.LENGTH_SHORT).show();
}
}
Try this out :
public class NetworkUtil {
public static int TYPE_WIFI = 1;
public static int TYPE_MOBILE = 2;
public static int TYPE_NOT_CONNECTED = 0;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static String getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
String status = null;
if (conn == NetworkUtil.TYPE_WIFI) {
status = "Wifi enabled";
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = "Mobile data enabled";
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = "Not connected to Internet";
}
return status;
}
}
Second create Broadcast receiver where you will get all this changes :
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
String status = NetworkUtil.getConnectivityStatusString(context);
Toast.makeText(context, status, Toast.LENGTH_LONG).show();
}
}
And don't forgot to add your broadcast into mainfest :
<receiver
android:name="YOUR PACKAGE NAME"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Also alternative of getType() : in kotlin
private fun isInternetAvailable(context: Context): Boolean {
var result = false
val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val networkCapabilities = connectivityManager.activeNetwork ?: return false
val actNw =
connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
result = when {
actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
else -> false
}
} else {
connectivityManager.run {
connectivityManager.activeNetworkInfo?.run {
result = when (type) {
ConnectivityManager.TYPE_WIFI -> true
ConnectivityManager.TYPE_MOBILE -> true
ConnectivityManager.TYPE_ETHERNET -> true
else -> false
}
}
}
}
return result
}
Alternative of getType() in java :
public static boolean isInternetAvailable(Context context) {
boolean result = false;
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (cm != null) {
NetworkCapabilities capabilities = cm.getNetworkCapabilities(cm.getActiveNetwork());
if (capabilities != null) {
if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
result = true;
} else if (capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
result = true;
}
}
}
} else {
if (cm != null) {
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (activeNetwork != null) {
// connected to the internet
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) {
result = true;
} else if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
result = true;
}
}
}
}
return result;
}

I m getting error in logcat like getNetworkInfo , wifi_p2p_statetracker

Error in Logcat
Below is my code for network connection,i m getting "Wifi_P2p_StateTracker" error, how to resolve this error,in AndroidManifest file i have declared all permissions.
public class ConnectionDetector {
private Context context;
public ConnectionDetector(Context context) {
this.context = context;
}
public boolean isConnected() {
boolean wifiDataAvailable = false;
boolean mobileDataAvailable = false;
try {
ConnectivityManager conManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] networkInfo = conManager.getAllNetworkInfo();
for (NetworkInfo netInfo : networkInfo) {
if (netInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (netInfo.isConnected())
wifiDataAvailable = true;
if (netInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (netInfo.isConnected())
mobileDataAvailable = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return wifiDataAvailable || mobileDataAvailable;
}
}

Check internet status from the main activity

I'm new student on android development, so I don't have the enough experience for coding, so I need the help from you...
I create a java class on android studio to check if there is an internet connection or not :
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
public class InternetStatus {
private static final String LOG_TAG ="InternetStatus";
public static boolean hasActiveInternetConnection(Context context) {
if (isNetworkAvailable((Activity) context)) {
try {
HttpURLConnection urlc = (HttpURLConnection) (new URL("http://www.google.com").openConnection());
urlc.setRequestProperty("User-Agent", "Test");
urlc.setRequestProperty("Connection", "close");
urlc.setConnectTimeout(1500);
urlc.connect();
return (urlc.getResponseCode() == 200);
} catch (IOException e) {
Log.e(LOG_TAG, "Error checking internet connection", e);
}
} else {
Log.d(LOG_TAG, "No network available!");
}
return false;
}
public static boolean isNetworkAvailable(Activity mActivity) {
Context context = mActivity.getApplicationContext();
ConnectivityManager connectivity = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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;
}
}
So, I have two questions :
1- is this the right code or I'm missing something ?
2- as you see this is a java class, if I create a button on my main activity to check if there is an internet connection or not !! how I can do that by importing this class or something like that ?!!
// Check if there is any connectivity for a Wifi network
public boolean isConnectedWifi(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI;
}
// Check if there is any connectivity for a mobile network
public boolean isConnectedMobile(){
NetworkInfo info = Connectivity.getNetworkInfo(Context);
return info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE;
}
// Check all connectivities whether available or not
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
return networkInfo != null && networkInfo.isConnected();
}
How to use?
For example, we need to check if the connectivity is available:
if(isNetworkAvailable()){
// do your thing here.
}
When the network is available, we need to check whether it is WiFi or Mobile network:
if(isConnectedWifi()){
// do your thing here with WiFi Network.
}
if(isConnectedMobile()){
// do your thing here with Mobile Network.
}
First of all, you must include a permission request in AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Then, create a method to check if internet connection is active:
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
}
In your MainActivity class
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
boolean isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
}
}
if you have a button
boolean isavailable ;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_camera);
Button someButton = (Button) findViewById(R.id.yourButton);
someButton.setOnClickListener(new onClickLIstener(){
isavailable = InternetStatus.hasActiveInternetConnection(getApplicationContext);
});
}
}
To check the connectivity status no need to connect to internet and get status code. Use below code.
public boolean isConnected() {
ConnectivityManager manager = (ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo info = manager.getActiveNetworkInfo();
if (info != null && info.isConnected()) {
return true;
} else {
return false;
}
}
Which will return true or false based on active network status.
On your button click simply call this function, If it returns true, there is a connection. If it returns false, there is no active internet connection.
Just Put info.isConnected() in your isNetworkAvailable function:
public static boolean isNetworkAvailable(Activity mActivity) {
...
if (connectivity == null) {
return false;
} else {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null && info.isConnected()) {
...
}
}
}
return false;
}
Most of the answers are outdated
fun isNetworkAvailable(context : Context): Boolean {
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
if (isAndroidVersionAboveLollipop()) {
val activeNetwork = connectivityManager.activeNetwork ?: return false
val networkCapabilities = connectivityManager.getNetworkCapabilities(activeNetwork) ?: return false
networkCapabilities.let {
return it.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) && it.hasCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
} else {
return connectivityManager.activeNetworkInfo?.isConnectedOrConnecting ?: false
}
}
fun isAndroidVersionAboveLollipop() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M

How to check if my app is using WIFI or 3G service

I am working on a messaging app, is there anyways or any API to identify the service provider name in android , also can anyone help me out how to programmatically check if the application is using WIFI connection or 3G service ? Please help me.
By this snippet block of code you can check all type networks in your device:
public boolean isNetworkAvailable() {
ConnectivityManager connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity == null) {
return false;
} else {
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 then test your network by this:
if (isNetworkAvailable()) {
//Network availabe...
} else {
Toast alrtMsg = Toast.makeText(this, "No network connection available !!!", Toast.LENGTH_LONG);
alrtMsg.setGravity(Gravity.CENTER, 0, 0);
alrtMsg.show();
}
This is a realy nice class to get the current connexion type and to be alert via listener of connexion update:
package com.android.aft.AFCoreTools;
import java.util.ArrayList;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class AFNetworkMonitoring {
public enum NetworkMode {
NotConnected,
ConnectedToWifi,
ConnectedTo3G,
};
public interface NetworkMonitoringInterface {
public void onNetworkUpdate(NetworkMode mode);
}
// Network connection
public NetworkMode mode = NetworkMode.NotConnected;
// Connection listener
private BroadcastReceiver mConnReceiver;
// Listeners
private ArrayList<NetworkMonitoringInterface> mListeners;
// Context
private Context mContext;
public AFNetworkMonitoring(Context ctx) {
this(ctx, null);
}
public AFNetworkMonitoring(Context ctx, NetworkMonitoringInterface listener) {
mContext = ctx;
addListener(listener);
// Create network state update
mConnReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
updateNetworkConnectionStatus();
}
};
mContext.registerReceiver(mConnReceiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
protected void updateNetworkConnectionStatus() {
ConnectivityManager conMgr = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = conMgr.getActiveNetworkInfo();
if (info == null || !info.isConnected() || !info.isAvailable()) {
DebugTools.d("Lost connection detected");
mode = NetworkMode.NotConnected;
notifyListener();
return;
}
NetworkInfo infoWifi = conMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if (infoWifi.isConnected() || infoWifi.isAvailable()) {
DebugTools.d("On connection wifi detected");
mode = NetworkMode.ConnectedToWifi;
notifyListener();
return;
}
DebugTools.d("On connection 3G detected");
mode = NetworkMode.ConnectedTo3G;
notifyListener();
}
protected void notifyListener() {
if (mListeners == null)
return ;
new AsyncTaskWrapper<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
// Nothing to do
return null;
}
#Override
protected void onPostExecute(Void result) {
for (NetworkMonitoringInterface l: mListeners)
l.onNetworkUpdate(mode);
};
}.executeParallel();
}
public void addListener(NetworkMonitoringInterface listener) {
if (listener == null)
return ;
if (mListeners == null)
mListeners = new ArrayList<AFNetworkMonitoring.NetworkMonitoringInterface>();
mListeners.add(listener);
}
public void removeListener(NetworkMonitoringInterface listener) {
if (mListeners == null)
return ;
mListeners.remove(listener);
}
}
LocationManager service = (LocationManager)getSystemService(getActivity().LOCATION_SERVICE);
boolean GPS_PROVIDER = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
boolean NETWORK_PROVIDER = service.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

Categories

Resources