I have created code which checks the internet connection at the start but I want it to keep checking for internet connection in the background and notify the user when connection is lost. I'm new to android so can you please write proper code and help me. This code works fine, I just want it so that it runs in the background to keep a check on internet.
public class isNetworkAvailable extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_is_network);
;
if(!isNetworkAvailable()){
//Create an alert dialog
AlertDialog.Builder Checkbuilder = new AlertDialog.Builder(isNetworkAvailable.this);
Checkbuilder.setIcon(R.drawable.error);
Checkbuilder.setTitle("Error!");
Checkbuilder.setMessage("Check Your Internet Connection.");
//Builder Retry Button
Checkbuilder.setPositiveButton("Retry", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
//Restart The Activity
Intent intent = getIntent();
finish();
startActivity(intent);
}
});
Checkbuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
}) ;
AlertDialog alert=Checkbuilder.create();
alert.show();
}
else {
if (isNetworkAvailable()){
Thread tr=new Thread(){
public void run(){
try {
sleep(4);
}
catch (Exception e){
e.printStackTrace();
}
finally {
Intent i = new Intent(isNetworkAvailable.this,MainActivity.class);
startActivity(i);
finish();
}}};tr.start();}}}private boolean isNetworkAvailable(){
ConnectivityManager connectivityManager=(ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo !=null;
}
}
Use ReactiveNetwork lib
ReactiveNetwork is an Android library listening network connection state and Internet connectivity. Library supports both new and legacy network monitoring strategies. Min SDK version = 9
Usage
add this to gradle
dependencies {
implementation 'com.github.pwittchen:reactivenetwork-rx2:3.0.2'
}
and in your activity
ReactiveNetwork.observeInternetConnectivity()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(isConnectedToInternet -> {
// do something with isConnectedToInternet value
changeOnlineStatus(isConnectedToInternet ? ConnectionQuality.EXCELLENT : ConnectionQuality.POOR);
});
it Observe Internet connectivity continuously
for more info link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With