Check Internet Connection in Android (API Level 29) Using Network Callback
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
You need to call the below method once. It register the callback and fire it when there is a change in network state. | |
Here I used a Global Static Variable, So I can use it to access the network state in anyware of the application. | |
*/ | |
// You need to pass the context when creating the class | |
public CheckNetwork(Context context) { | |
this.context = context; | |
} | |
// Network Check | |
public void registerNetworkCallback() | |
{ | |
try { | |
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); | |
NetworkRequest.Builder builder = new NetworkRequest.Builder(); | |
connectivityManager.registerDefaultNetworkCallback(new ConnectivityManager.NetworkCallback(){ | |
@Override | |
public void onAvailable(Network network) { | |
Variables.isNetworkConnected = true; // Global Static Variable | |
} | |
@Override | |
public void onLost(Network network) { | |
Variables.isNetworkConnected = false; // Global Static Variable | |
} | |
} | |
); | |
Variables.isNetworkConnected = false; | |
}catch (Exception e){ | |
Variables.isNetworkConnected = false; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Variables { | |
// Global variable used to store network state | |
public static boolean isNetworkConnected = false; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class MainActivity extends AppCompatActivity { | |
@Override | |
protected void onCreate(Bundle savedInstanceState) { | |
super.onCreate(savedInstanceState); | |
setContentView(R.layout.activity_main); | |
// Register Callback - Call this in your app start! | |
CheckNetwork network = new CheckNetwork(getApplicationContext()); | |
network.registerNetworkCallback(); | |
// Check network connection | |
if (Variables.isNetworkConnected){ | |
// Internet Connected | |
}else{ | |
// Not Connected | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment