Android run code if connected to internet / wifi - java

I have an application that runs on boot up and that works great, my new problem is that my app requires an internet connection and my app gets booted up before there is an internet connect, thus I get a 404 error inside my app,
is there away to put this code below in a loop to if internet connection fails, them try the code again, like a try catch sorta thing. I am very new to java and would have no idea how to do this. Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Loop Here to test if internet connection, if not try again
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://example.com");
}
I have also tried the following with a try and catch by now my application will not run altogether:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress("www.google.com",80);
try{
socket.connect(address, 3000);
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://example.com");
} catch (Exception e){
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://example.com");
} finally {
try {socket.close();}
catch (Exception e){}
}
}
PLEASE HELP :(
And I have also been playing with this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread t = new Thread();
try{
while(!isConnected(WifiExplorerActivity.this)){
Thread.sleep(1000);
}
} catch (Exception e){
}
WebView myWebView = (WebView) findViewById(R.id.webview);
myWebView.setWebViewClient(new WebViewClient());
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.loadUrl("http://example.com");
}
and adding this to my Manifest:
<activity android:name=".WifiExplorerActivity" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</activity>

You better try a BroadcastReceiver :
use : either use the whole class or just call the static methods
public class NetworkManager extends BroadcastReceiver {
protected static final String TAG = NetworkManager.class.getSimpleName(); // log
protected Context mContext;
protected boolean mNoConnectivity;
protected String mReason;
protected boolean mIsFailover;
protected static boolean mIsConnected = false;
protected static boolean mIsConnectivityGood = true;
public NetworkManager(Context context) {
this.mContext = context;
}
public void registerReceivers() {
mContext.registerReceiver(this, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) mContext.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;
}
/**
* #param context
* #return
*/
public static NetworkInfo getNetworkInfo(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo();
}
/**
* #param context
* #return
*/
public static boolean isConnected(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected());
}
/**
* #param context
* #return
*/
public static boolean isConnectedWifi(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_WIFI);
}
/**
* #param context
* #return
*/
public static boolean isConnectedMobile(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && info.getType() == ConnectivityManager.TYPE_MOBILE);
}
/**
* #param context
* #return
*/
public static boolean isConnectedFast(Context context) {
NetworkInfo info = getNetworkInfo(context);
return (info != null && info.isConnected() && isConnectionFast(info.getType(), info.getSubtype()));
}
protected static boolean isConnectionFast(int type, int subType) {
if (type == ConnectivityManager.TYPE_WIFI) {
return true;
} else if (type == ConnectivityManager.TYPE_MOBILE) {
switch (subType) {
case TelephonyManager.NETWORK_TYPE_1xRTT:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_CDMA:
return false; // ~ 14-64 kbps
case TelephonyManager.NETWORK_TYPE_EDGE:
return false; // ~ 50-100 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_0:
return true; // ~ 400-1000 kbps
case TelephonyManager.NETWORK_TYPE_EVDO_A:
return true; // ~ 600-1400 kbps
case TelephonyManager.NETWORK_TYPE_GPRS:
return false; // ~ 100 kbps
case TelephonyManager.NETWORK_TYPE_HSDPA:
return true; // ~ 2-14 Mbps
case TelephonyManager.NETWORK_TYPE_HSPA:
return true; // ~ 700-1700 kbps
case TelephonyManager.NETWORK_TYPE_HSUPA:
return true; // ~ 1-23 Mbps
case TelephonyManager.NETWORK_TYPE_UMTS:
return true; // ~ 400-7000 kbps
case TelephonyManager.NETWORK_TYPE_UNKNOWN:
default:
return false;
}
} else {
return false;
}
}
#Override
public void onReceive(Context context, Intent intent) {
mNoConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
mIsFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
//
if (mNoConnectivity) {
mIsConnected = false;
} else {
if (isConnectedFast(mContext)) {
mIsConnectivityGood = true;
} else {
mIsConnectivityGood = false;
}
mIsConnected = true;
}
}
}

Its Should work:
public class SMSReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);//make it enabled
if(wifiManager.isWifiEnabled()){//if its enabled
//your code...
}
}
}
your should have on your manifest:
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>//if you want to change it

This method works for me:
public static boolean isConnectivityOn(Context ctx) {
boolean resCode = false;
try {
ConnectivityManager cm =
(ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
resCode = cm.getActiveNetworkInfo().isConnectedOrConnecting();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return resCode;
}
Taking care having
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
in the Manifest

Related

Connect to wifi programmatically on android Q(android10) to transfer files

I'm building a file sharing app like (SHAREit, xender,...). My code is working fine on api level 28 and below. But I'm not able to make it work on android 10. I tried wifisuggestion and WifiNetworkSpecifier api but still not able to share files. (how could apps like SHARE it connect to wifi programmatically on android 10 without even using WifiNetworkSpecifier )?
Here' my code
Manifest
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.android.share">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.WRITE_SETTINGS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Connection Utils
public class ConnectionUtils{ ....initialization...
mWifiManager = (WifiManager) getContext().getApplicationContext().getSystemService(Context.WIFI_SERVICE);
mConnectivityManager = (ConnectivityManager) getContext().getSystemService(Context.CONNECTIVITY_SERVICE);
}public static ConnectionUtils getInstance(Context context) {
return new ConnectionUtils(context);
}
public static String getCleanNetworkName(String networkName) {
if (networkName == null)
return "";
return networkName.replace("\"", "");
}
public boolean canAccessLocation() {
return hasLocationPermission(getContext()) && isLocationServiceEnabled();
}
public boolean canReadScanResults() {
return getWifiManager().isWifiEnabled() && (Build.VERSION.SDK_INT < 23 || canAccessLocation());
}
public boolean disableCurrentNetwork() {
return isConnectedToAnyNetwork()
&& getWifiManager().disconnect()
&& getWifiManager().disableNetwork(getWifiManager().getConnectionInfo().getNetworkId());
}
#WorkerThread
public String establishHotspotConnection(final Interrupter interrupter,
final NetworkDeviceListAdapter.HotspotNetwork hotspotNetwork,
final ConnectionCallback connectionCallback) {
final int pingTimeout = 1000; // ms
final long startTime = System.currentTimeMillis();
String remoteAddress = null;
boolean connectionToggled = false;
boolean secondAttempt = false;
boolean thirdAttempt = false;
while (true) {
int passedTime = (int) (System.currentTimeMillis() - startTime);
if (passedTime >= 10000 && !secondAttempt) {
secondAttempt = true;
disableCurrentNetwork();
connectionToggled = false;
}
if (passedTime >= 20000 && !thirdAttempt) {
thirdAttempt = true;
disableCurrentNetwork();
connectionToggled = false;
}
if (!getWifiManager().isWifiEnabled()) {
Log.d(TAG, "establishHotspotConnection(): Wifi is off. Making a request to turn it on");
if (!getWifiManager().setWifiEnabled(true)) {
Log.d(TAG, "establishHotspotConnection(): Wifi was off. The request has failed. Exiting.");
break;
}
}
else if (!isConnectedToNetwork(hotspotNetwork) && !connectionToggled) {
Log.d(TAG, "establishHotspotConnection(): Requested network toggle");
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q){
toggleConnection(hotspotNetwork);
}
else{
connect(hotspotNetwork.SSID,hotspotNetwork.password);
}
connectionToggled = true;
} else {
Log.d(TAG, "establishHotspotConnection(): Waiting to connect to the server");
final DhcpInfo routeInfo = getWifiManager().getDhcpInfo();
//Log.w(TAG, String.format("establishHotspotConnection(): DHCP: %s", routeInfo));
if (routeInfo != null && routeInfo.gateway != 0) {
final String testedRemoteAddress = NetworkUtils.convertInet4Address(routeInfo.gateway);
Log.d(TAG, String.format("establishHotspotConnection(): DhcpInfo: gateway: %s dns1: %s dns2: %s ipAddr: %s serverAddr: %s netMask: %s",
testedRemoteAddress,
NetworkUtils.convertInet4Address(routeInfo.dns1),
NetworkUtils.convertInet4Address(routeInfo.dns2),
NetworkUtils.convertInet4Address(routeInfo.ipAddress),
NetworkUtils.convertInet4Address(routeInfo.serverAddress),
NetworkUtils.convertInet4Address(routeInfo.netmask)));
Log.d(TAG, "establishHotspotConnection(): There is DHCP info provided waiting to reach the address " + testedRemoteAddress);
if (UIConnectionUtils.isOSAbove(Build.VERSION_CODES.P)
? NetworkUtils.ping(testedRemoteAddress, pingTimeout)
: NetworkUtils.ping(testedRemoteAddress)) {
Log.d(TAG, "establishHotspotConnection(): AP has been reached. Returning OK state.");
remoteAddress = testedRemoteAddress;
break;
} else
Log.d(TAG, "establishHotspotConnection(): Connection check ping failed");
} else
Log.d(TAG, "establishHotspotConnection(): No DHCP provided. Looping...");
}
if (connectionCallback.onTimePassed(1000, passedTime) || interrupter.interrupted()) {
Log.d(TAG, "establishHotspotConnection(): Timed out or onTimePassed returned true. Exiting...");
break;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}
return remoteAddress;
}
public boolean hasLocationPermission(Context context) {
return ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
public Context getContext() {
return mContext;
}
public ConnectivityManager getConnectivityManager() {
return mConnectivityManager;
}
public HotspotUtils getHotspotUtils() {
return mHotspotUtils;
}
public LocationManager getLocationManager() {
return mLocationManager;
}
public WifiManager getWifiManager() {
return mWifiManager;
}
public boolean isConnectionSelfNetwork() {
WifiInfo wifiInfo = getWifiManager().getConnectionInfo();
return wifiInfo != null
&& getCleanNetworkName(wifiInfo.getSSID()).startsWith(AppConfig.PREFIX_ACCESS_POINT);
}
public boolean isConnectedToAnyNetwork() {
NetworkInfo info = getConnectivityManager().getActiveNetworkInfo();
return info != null
&& info.getType() == ConnectivityManager.TYPE_WIFI
&& info.isConnected();
}
public boolean isConnectedToNetwork(NetworkDeviceListAdapter.HotspotNetwork hotspotNetwork) {
if (!isConnectedToAnyNetwork())
return false;
if (hotspotNetwork.BSSID != null)
return hotspotNetwork.BSSID.equals(getWifiManager().getConnectionInfo().getBSSID());
return hotspotNetwork.SSID.equals(getCleanNetworkName(getWifiManager().getConnectionInfo().getSSID()));
}
public boolean isLocationServiceEnabled() {
return mLocationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}
public boolean isMobileDataActive() {
return mConnectivityManager.getActiveNetworkInfo() != null
&& mConnectivityManager.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_MOBILE;
}
public boolean toggleConnection(NetworkDeviceListAdapter.HotspotNetwork hotspotNetwork) {
if (!isConnectedToNetwork(hotspotNetwork)) {
if (isConnectedToAnyNetwork())
disableCurrentNetwork();
WifiConfiguration config = new WifiConfiguration();
config.SSID = String.format("\"%s\"", hotspotNetwork.SSID);
...........(configuation)
try {
int netId = getWifiManager().addNetwork(config);
if (/*Build.VERSION.SDK_INT >= */UIConnectionUtils.isOSAbove(Build.VERSION_CODES.M)) {
#SuppressLint("MissingPermission") List<WifiConfiguration> list = getWifiManager().getConfiguredNetworks();
for (WifiConfiguration hotspotWifi : list) {
if (hotspotWifi.SSID != null && hotspotWifi.SSID.equalsIgnoreCase(config.SSID)) {
getWifiManager().disconnect();
getWifiManager().enableNetwork(hotspotWifi.networkId, true);
return getWifiManager().reconnect();
}
}
} else {
getWifiManager().disconnect();
getWifiManager().enableNetwork(netId, true);
return getWifiManager().reconnect();
}
} catch (Exception exp) {
disableCurrentNetwork();
return false;
}
}
disableCurrentNetwork();
return false;
}
public interface ConnectionCallback {
boolean onTimePassed(int delimiter, long timePassed);
}
#RequiresApi(api = Build.VERSION_CODES.Q)
public boolean connect(String ssid, String password){
if (mConnectivityManager == null) {
return false;
}
NetworkSpecifier networkSpecifier;
networkSpecifier = new WifiNetworkSpecifier.Builder()
.setSsid(ssid)
.setWpa2Passphrase(password)
.build();
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.setNetworkSpecifier(networkSpecifier)
.removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.build();
mConnectivityManager.requestNetwork(networkRequest, mNetworkCallback);
return true;
}
#RequiresApi(api = Build.VERSION_CODES.Q)
private ConnectivityManager.NetworkCallback mNetworkCallback = new ConnectivityManager.NetworkCallback(){
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
//phone is connected to wifi network
mConnectivityManager.bindProcessToNetwork(network);
}
...implement members}
UiConnectionUtil
public class UIConnectionUtils{ initialize .... public void makeAcquaintance(final Activity activity, final UITask task, final Object object, final int accessPin,
final NetworkDeviceLoader.OnDeviceRegisteredListener registerListener)
{
WorkerService.RunningTask runningTask = new WorkerService.RunningTask()
{
private boolean mConnected = false;
private String mRemoteAddress;
#Override
public void onRun()
{
final DialogInterface.OnClickListener retryButtonListener = new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
makeAcquaintance(activity, task, object, accessPin, registerListener);
}
};
try {
if (object instanceof NetworkDeviceListAdapter.HotspotNetwork) {
mRemoteAddress = getConnectionUtils().establishHotspotConnection(getInterrupter(),
(NetworkDeviceListAdapter.HotspotNetwork) object,
new ConnectionUtils.ConnectionCallback()
{
#Override
public boolean onTimePassed(int delimiter, long timePassed)
{
return timePassed >= 30000;
}
});
} else if (object instanceof String)
mRemoteAddress = (String) object;
if (mRemoteAddress != null) {
mConnected = setupConnection(activity, mRemoteAddress, accessPin, new NetworkDeviceLoader.OnDeviceRegisteredListener()
{
#Override
public void onDeviceRegistered(final AccessDatabase database, final NetworkDevice device, final NetworkDevice.Connection connection)
{
// we may be working with direct IP scan
new Handler(Looper.getMainLooper()).post(new Runnable()
{
#Override
public void run()
{
if (registerListener != null)
registerListener.onDeviceRegistered(database, device, connection);
}
});
}
}, retryButtonListener) != null;
}
if (!mConnected && !getInterrupter().interruptedByUser())
new Handler(Looper.getMainLooper()).post(new Runnable()
{
#Override
public void run()
{
if (!activity.isFinishing()) {
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(activity)
.setMessage(R.string.mesg_connectionFailure)
.setNegativeButton(R.string.butn_close, null)
.setPositiveButton(R.string.butn_retry, retryButtonListener);
if (object instanceof NetworkDevice)
dialogBuilder.setTitle(((NetworkDevice) object).nickname);
dialogBuilder.show();
}
}
});
} catch (Exception e) {
} finally {
new Handler(Looper.getMainLooper()).post(new Runnable()
{
#Override
public void run()
{
if (task != null && !activity.isFinishing())
task.updateTaskStopped();
}
});
}
// We can't add dialog outside of the else statement as it may close other dialogs as well
}
}.setTitle(activity.getString(R.string.mesg_completing))
.setIconRes(R.drawable.ic_compare_arrows_white_24dp_static);
runningTask.run(activity);
if (task != null)
task.updateTaskStarted(runningTask.getInterrupter());
}
public boolean notifyWirelessRequestHandled()
{
boolean returnedState = mWirelessEnableRequested;
mWirelessEnableRequested = false;
return returnedState;
}
#WorkerThread
public NetworkDevice setupConnection(final Activity activity,
final String ipAddress,
final int accessPin,
final NetworkDeviceLoader.OnDeviceRegisteredListener listener,
final DialogInterface.OnClickListener retryButtonListener)
{
return CommunicationBridge.connect(AppUtils.getDatabase(activity), NetworkDevice.class, new CommunicationBridge.Client.ConnectionHandler()
{
#Override
public void onConnect(CommunicationBridge.Client client)
{
try {
client.setSecureKey(accessPin);
CoolSocket.ActiveConnection activeConnection = client.connectWithHandshake(ipAddress, false);
NetworkDevice device = client.loadDevice(activeConnection);
activeConnection.reply(new JSONObject()
.put(Keyword.REQUEST, Keyword.REQUEST_ACQUAINTANCE)
.toString());
JSONObject receivedReply = new JSONObject(activeConnection.receive().response);
if (receivedReply.has(Keyword.RESULT)
&& receivedReply.getBoolean(Keyword.RESULT)
&& device.deviceId != null) {
final NetworkDevice.Connection connection = NetworkDeviceLoader.processConnection(AppUtils.getDatabase(activity), device, ipAddress);
device.lastUsageTime = System.currentTimeMillis();
device.tmpSecureKey = accessPin;
device.isRestricted = false;
device.isTrusted = true;
AppUtils.getDatabase(activity).publish(device);
if (listener != null)
listener.onDeviceRegistered(AppUtils.getDatabase(activity), device, connection);
} else
showConnectionRejectionInformation(activity, device, receivedReply, retryButtonListener);
client.setReturn(device);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public interface RequestWatcher
{
void onResultReturned(boolean result, boolean shouldWait);
}}

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;
}

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

Connection status - how to call method from another class

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;
}
}

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