When connection get back I want to run this task, I want to call NewortchangeReceiver() constructor. I wrote "android.net.conn.CONNECTIVITY_CHANGE" in Mainactivity IntentFilter because "android.net.conn.CONNECTIVITY_CHANGE" not work in androidmanifest.xml in android N (7). I want to automatic reload webview at internet connection change.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wvDailyDarshan = (WebView) findViewById(R.id.wvDailyDarshan);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(new NetworkChangeReceiver(), intentFilter);
Boolean connection = isNetworkConnected();
if (connection == false) {
Snackbar.make(this.getWindow().getDecorView().findViewById(android.R.id.content), "Please check your Internet Connection", Snackbar.LENGTH_SHORT).show();
} else if (connection == true) {
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
//wvDailyDarshan.loadUrl("http://www.swaminarayanbhagwan.com/daily-darshan/");
wvDailyDarshan.setWebViewClient(new myWebClient());
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
wvDailyDarshan.getSettings().setBuiltInZoomControls(true);
wvDailyDarshan.getSettings().setDisplayZoomControls(false);
wvDailyDarshan.loadUrl("https://www.google.co.in/");
}
}
What I get from your question is that you want to get callback when there is change in connectivity.
So I'll answer for that.
NetworkChangeReceiver:
public class NetworkChangeReceiver extends BroadcastReceiver {
ConnectionChangeCallback connectionChangeCallback;
#Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null
&& activeNetwork.isConnectedOrConnecting();
if (connectionChangeCallback != null) {
connectionChangeCallback.onConnectionChange(isConnected);
}
}
public void setConnectionChangeCallback(ConnectionChangeCallback
connectionChangeCallback) {
this.connectionChangeCallback = connectionChangeCallback;
}
public interface ConnectionChangeCallback {
void onConnectionChange(boolean isConnected);
}
}
Now your Activity should call setConnectionChangeCallback on BraodCastReceiver ie NetworkChangeReceiver's object and provide ConnectionChangeCallback's implementation.
Which may look like this.
Activity:
public class YourActivity implments NetworkChangeReceiver.ConnectionChangeCallback
{
#Override
protected void onCreate(Bundle savedInstanceState) {
.....
IntentFilter intentFilter = new
IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
NetworkChangeReceiver networkChangeReceiver = new NetworkChangeReceiver();
registerReceiver(networkChangeReceiver, intentFilter);
networkChangeReceiver.setConnectionChangeCallback(this);
}
#Override
public void onConnectionChange(boolean isConnected) {
if(isConnected){
// will be called when internet is back
}
else{
// will be called when internet is gone.
}
}
}
You can create a new method, which will call itself if internet is not connected. A rough example is below. Change it to more efficient way.
private boolean shoudShowSnackbar = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wvDailyDarshan = (WebView) findViewById(R.id.wvDailyDarshan);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
context.registerReceiver(new NetworkChangeReceiver(), intentFilter);
doThisThingIfFoundInternet();
}
private void doThisThingIfFoundInternet() {
if (isNetworkConnected()) {
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
//wvDailyDarshan.loadUrl("http://www.swaminarayanbhagwan.com/daily-darshan/");
wvDailyDarshan.setWebViewClient(new myWebClient());
wvDailyDarshan.getSettings().setJavaScriptEnabled(true);
wvDailyDarshan.getSettings().setBuiltInZoomControls(true);
wvDailyDarshan.getSettings().setDisplayZoomControls(false);
wvDailyDarshan.loadUrl("https://www.google.co.in/");
}else{
if (this.shoudShowSnackbar) {
Snackbar.make(this.getWindow().getDecorView().findViewById(android.R.id.content), "Please check your Internet Connection", Snackbar.LENGTH_SHORT).show();
shoudShowSnackbar = !shoudShowSnackbar;
}
doThisThingIfFoundInternet();
}
}
I'm trying to create an app that checks for internet connection when it opens. I want it to display a loading screen as long as there is not internet connection and a message. The loading screen activity is activity_main.xml. The problem is that because I'm calling LoggingIn method from itself, it keeps repeating it untill I have internet connection, but the problem is that for some reason it just won't load the activity itself. It just shows me a blank screen. When I don't run LoggingIn the activity does work.
Please help is there any other way to do this?
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LoggingIn();
}
public void LoggingIn ()
{
if (isNetworkAvailable())
{
if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
{
findViewById(R.id.InternetConnection).setVisibility(View.GONE);
}
AttemptLoggingIn();
}
else
{
findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
LoggingIn();
}
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
Use background threads instead of your very strange method.
For example,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startCheck();
}
private boolean startCheck() {
new Thread(new Runnable() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
findViewById(R.id.InternetConnection).setVisibility(View.VISIBLE);
}
});
while(!isNetworkAvailable()) {
try {
Thread.sleep(100L);// 100 ms sleep
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if (findViewById(R.id.InternetConnection).getVisibility() == View.VISIBLE)
{
findViewById(R.id.InternetConnection).setVisibility(View.GONE);
}
AttemptLoggingIn();
}
});
}
}).start();
}
You don't need to call LoggingIn() to monitor network changes.
ConnectivityManager automatically broadcasts the CONNECTIVITY_ACTION action whenever the connectivity details change.This article can be really useful for you:
http://www.androidhive.info/2012/07/android-detect-internet-connection-status/
I am trying to do a task where check the internet and then alert the user using an alertdialog using a connectivity manager.. does anybody know how I would implement this in my main activity when both my buttons are pressed ( separately)?
public class MainActivity extends Activity implements OnClickListener {
Button login, register;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login = (Button) findViewById(R.id.login_bt);
register = (Button) findViewById(R.id.register_bt);
login.setOnClickListener(this);
register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = null;
if (v.getId() == login.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
} else if (v.getId() == register.getId()) {
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
Check for internet connection
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo ni = manager.getActiveNetworkInfo();
boolean connected=ni != null && ni.getState() == NetworkInfo.State.CONNECTED;
if(connected){
//network connected
}else{
//network disconnected
}
Manifest
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
Create a new class CustomClickListener :
class CustomClickListener implements View.OnClickListener {
#Override
public void onClick(View v) {
if(isOnline()) {
Intent i = null;
i = new Intent(getBaseContext(), RegistrationActivity.class);
startActivity(i);
}
}
}
And in the OnCreate method :
login.setOnClickListener(new CustomClickListener());
register.setOnClickListener(new CustomClickListener());
This method checks for Internet connection :
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
I have a splashscreen (for try Internet), if we can't connect, we don't launch app.
So, i have try to found one java class on internet and i have found that :https://stackoverflow.com/a/6987498/5070495
I have adapt the code, but i have an error in
if (SplashScreen.getInstance(this).isOnline()) {
Error :
getInstance(android.content.Context')in 'com.srazzz.package.Splashscreen' cannot be applied to '(anonymous java.lang.thread')
All my class
public class SplashScreen extends Activity {
static Context context;
ConnectivityManager connectivityManager;
NetworkInfo wifiInfo, mobileInfo;
boolean connected = false;
private static SplashScreen instance = new SplashScreen();
public static SplashScreen getInstance(Context ctx) {
context = ctx.getApplicationContext();
return instance;
}
public boolean isOnline() {
try {
connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
connected = networkInfo != null && networkInfo.isAvailable() &&
networkInfo.isConnected();
return connected;
} catch (Exception e) {
System.out.println("CheckConnectivity Exception: " + e.getMessage());
Log.v("connectivity", e.toString());
}
return connected;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
if (SplashScreen.getInstance(this).isOnline()) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
} else {
//Toast t = Toast.makeText("test").show();
//Log.v("Home", "############################You are not online!!!!");
Intent i = new Intent(SplashScreen.this, chatonly.class);
startActivity(i);
}
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
Use like this,
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (isOnline()) {
Intent i = new Intent(SplashScreen.this, MainActivity.class);
startActivity(i);
} else {
//Toast t = Toast.makeText("test").show();
//Log.v("Home", "############################You are not online!!!!");
Intent i = new Intent(SplashScreen.this, chatonly.class);
startActivity(i);
}
}
}, 3000);
Try writing out fully qualified thread class name as example
new java.lang.Thread(new Runnable() {
public void run() {
if (SplashScreen.getInstance(this).isOnline()) {
//do stuff here} else{
//Don't do stuff} }
}).start();
I already have this code which listens to connectivity change -
public class NetworkStateReceiver extends BroadcastReceiver
{
public void onReceive(Context context, Intent intent)
{
Log.d("app","Network connectivity change");
if(intent.getExtras() != null)
{
NetworkInfo ni = (NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni != null && ni.getState() == NetworkInfo.State.CONNECTED)
{
Log.i("app", "Network " + ni.getTypeName() + " connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE))
{
Log.d("app", "There's no network connectivity");
}
}
}
And I check Internet connectivity using this code - Internet Check
But the problem is that if network suddenly loses internet connection without any connectivity change, this code is useless. Is there any way to create Broadcast Receiver listener for Internet connectivity change? I have a web app and sudden Internet connectivity changes can cause problems.
Try this
public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;
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 int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
And for the BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
Log.e("Sulod sa network reciever", "Sulod sa network reciever");
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new ForceExitPause(context).execute();
} else {
new ResumeForceExitPause(context).execute();
}
}
}
}
Don't forget to put this into your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
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>
Hope this will help you Cheers!
ConnectivityAction is deprecated in api 28+. Instead you can use registerDefaultNetworkCallback as long as you support api 24+.
In Kotlin:
val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityManager?.let {
it.registerDefaultNetworkCallback(object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) {
//take action when network connection is gained
}
override fun onLost(network: Network?) {
//take action when network connection is lost
}
})
}
Here's the Java code using registerDefaultNetworkCallback (and registerNetworkCallback for API < 24):
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
// network available
}
#Override
public void onLost(Network network) {
// network unavailable
}
};
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
Update:
Apps targeting Android 7.0 (API level 24) and higher do not receive
CONNECTIVITY_ACTION broadcasts if they declare the broadcast receiver
in their manifest. Apps will still receive CONNECTIVITY_ACTION
broadcasts if they register their BroadcastReceiver with
Context.registerReceiver() and that context is still valid.
You need to register the receiver via registerReceiver() method:
IntentFilter intentFilter = new IntentFilter("android.net.conn.CONNECTIVITY_CHANGE");
mCtx.registerReceiver(new NetworkBroadcastReceiver(), intentFilter);
This should work:
public class ConnectivityChangeActivity extends Activity {
private BroadcastReceiver networkChangeReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Log.d("app","Network connectivity change");
}
};
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkChangeReceiver, intentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(networkChangeReceiver);
}
}
I used this method as a connection listener. Working for Lolipop+, Android JAVA language.
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkRequest networkRequest = new NetworkRequest.Builder().build();
connectivityManager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(Network network) {
super.onAvailable(network);
Log.i("Tag", "active connection");
}
#Override
public void onLost(Network network) {
super.onLost(network);
Log.i("Tag", "losing active connection");
isNetworkConnected();
}
});
}
private boolean isNetworkConnected() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (!(cm.getActiveNetworkInfo() != null && cm.getActiveNetworkInfo().isConnected())) {
//Do something
return false;
}
return true;
}
And also add this permission in your Android Manifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Hello from the year 2022.
In my custom view model I observe network status changes like this:
public class MyViewModel extends AndroidViewModel {
private final MutableLiveData<Boolean> mConnected = new MutableLiveData<>();
public MyViewModel(Application app) {
super(app);
ConnectivityManager manager = (ConnectivityManager)app.getSystemService(Context.CONNECTIVITY_SERVICE);
if (manager == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
mConnected.setValue(true);
return;
}
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.build();
manager.registerNetworkCallback(networkRequest, new ConnectivityManager.NetworkCallback() {
Set<Network> availableNetworks = new HashSet<>();
public void onAvailable(#NonNull Network network) {
availableNetworks.add(network);
mConnected.postValue(!availableNetworks.isEmpty());
}
public void onLost(#NonNull Network network) {
availableNetworks.remove(network);
mConnected.postValue(!availableNetworks.isEmpty());
}
public void onUnavailable() {
availableNetworks.clear();
mConnected.postValue(!availableNetworks.isEmpty());
}
});
}
#NonNull
public MutableLiveData<Boolean> getConnected() {
return mConnected;
}
}
And then in my Activity or Fragment I can change the UI by observing:
#Override
protected void onCreate(Bundle savedInstanceState) {
MyViewModel vm = new ViewModelProvider(this).get(MyViewModel.class);
vm.getConnected().observe(this, connected -> {
// TODO change GUI depending on the connected value
});
}
first add dependency in your code as implementation 'com.treebo:internetavailabilitychecker:1.0.4'
implements your class with InternetConnectivityListener.
public class MainActivity extends AppCompatActivity implements InternetConnectivityListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InternetAvailabilityChecker.init(this);
mInternetAvailabilityChecker = InternetAvailabilityChecker.getInstance();
mInternetAvailabilityChecker.addInternetConnectivityListener(this);
}
#Override
public void onInternetConnectivityChanged(boolean isConnected) {
if (isConnected) {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle(" internet is connected or not");
alertDialog.setMessage("connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
else {
alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("internet is connected or not");
alertDialog.setMessage("not connected");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
}
}
I have noticed that no one mentioned WorkManger solution which is better and support most of android devices.
You should have a Worker with network constraint AND it will fired only if network available, i.e:
val constraints = Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build()
val worker = OneTimeWorkRequestBuilder<MyWorker>().setConstraints(constraints).build()
And in worker you do whatever you want once connection back, you may fire the worker periodically .
i.e:
inside dowork() callback:
notifierLiveData.postValue(info)
According to the official docs:
Define network request
private val networkRequest = NetworkRequest.Builder().apply {
// To check wifi and cellular networks for internet availability
addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Capabilities can be verified starting Android 6.0.
// For a network with NET_CAPABILITY_INTERNET,
// it means that Internet connectivity was successfully detected
addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
// Indicates that this network is available for use by apps,
// and not a network that is being kept up in the background
// to facilitate fast network switching.
addCapability(NetworkCapabilities.NET_CAPABILITY_FOREGROUND)
}
}.build()
Configure a network callback
private val networkCallback = object : ConnectivityManager.NetworkCallback() {
private val networks = mutableListOf<Network>()
override fun onAvailable(network: Network) {
super.onAvailable(network)
networks.add(network)
Log.d("Has network --->", networks.any().toString())
}
override fun onLost(network: Network) {
super.onLost(network)
networks.remove(network)
Log.d("Has network --->", networks.any().toString())
}
}
Register for network updates
val connectivityService =
applicationContext.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
connectivityService.registerNetworkCallback(networkRequest, networkCallback)
ref https://developer.android.com/training/monitoring-device-state/connectivity-status-type
To specify the transport type of the network, such as Wi-Fi or
cellular connection, and the currently connected network's
capabilities, such as internet connection, you must configure a
network request.
Declare a NetworkRequest that describes your app’s network connection
needs. The following code creates a request for a network that is
connected to the internet and uses either a Wi-Fi or cellular
connection for the transport type.
add this in onCreate
NetworkRequest networkRequest = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
.addTransportType(NetworkCapabilities.TRANSPORT_CELLULAR)
.build();
Configure a network callback When you register the NetworkRequest with
the ConnectivityManager, you must implement a NetworkCallback to
receive notifications about changes in the connection status and
network capabilities.
The most commonly implemented functions in the NetworkCallback include
the following:
onAvailable() indicates that the device is connected to a new network
that satisfies the capabilities and transport type requirements
specified in the NetworkRequest. onLost() indicates that the device
has lost connection to the network. onCapabilitiesChanged() indicates
that the capabilities of the network have changed. The
NetworkCapabilities object provides information about the current
capabilities of the network.
add listener
private ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
#Override
public void onAvailable(#NonNull Network network) {
super.onAvailable(network);
}
#Override
public void onLost(#NonNull Network network) {
super.onLost(network);
}
#Override
public void onCapabilitiesChanged(#NonNull Network network, #NonNull NetworkCapabilities networkCapabilities) {
super.onCapabilitiesChanged(network, networkCapabilities);
final boolean unmetered = networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
}};
Register for network updates After you declare the NetworkRequest and
NetworkCallback, use the requestNetwork() or registerNetworkCallback()
functions to search for a network to connect from the device that
satisfies the NetworkRequest. The status is then reported to the
NetworkCallback.
Register in onCreate
ConnectivityManager connectivityManager =
(ConnectivityManager) getSystemService(ConnectivityManager.class);
connectivityManager.requestNetwork(networkRequest, networkCallback);
implementation 'com.treebo:internetavailabilitychecker:1.0.1'
public class MyApp extends Application {
#Override
public void onCreate() {
super.onCreate();
InternetAvailabilityChecker.init(this);
}
#Override
public void onLowMemory() {
super.onLowMemory();
InternetAvailabilityChecker.getInstance().removeAllInternetConnectivityChangeListeners();
}
}