DEV Community

Rodrigo Garcia Trejo
Rodrigo Garcia Trejo

Posted on

1 1

Mini-tutorial Android Studio: Revisar conexión a internet

Hola de nuevo a un mini-tutorial de Android Studio.

En esta ocasión les enseñare a revisar si en su dispositivo hay conexión a internet

¡¡¡Vamos al código!!!


AndroidManifest.xml

En nuestro AndroidManifest.xml agregaremos los permisos para eso tendremos que agregar arriba de nuestro application

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    ....
    <application
        android:allowBackup="false"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
Enter fullscreen mode Exit fullscreen mode

MainActivity.java

En nuestro MainActivity utilizaremos el objeto ConnectivityManager y creamos un objeto Networkinfo

ConnectivityManager con = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo = con.getActiveNetworkInfo();
Enter fullscreen mode Exit fullscreen mode

Ya teniendo el objeto networkInfo podremos revisar la conexión.

Ahora con un simple if revisamos si hay conexión a internet

    if(networkInfo!=null && networkInfo.isConnected())
        {
           Toast.makeText(getApplicationContext(), "Si hay conexión a internet", Toast.LENGTH_LONG).show();
        }else
        {
            Toast.makeText(context, "Necesitas conectarte a internet", Toast.LENGTH_LONG).show();
        }
Enter fullscreen mode Exit fullscreen mode

Fin

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide →

Top comments (1)

Collapse
 
bikashdey profile image
Biki Dey

Keep posting this type of awesome article. Economics Tuition

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs