Wednesday, September 30, 2015

android - How to detect connection type

activity_main.xml

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp"
    tools:context=".MainActivity"
    android:background="#cedfde"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif-condensed"
        android:textSize="25dp"
        android:textStyle="italic"
        android:padding="15dp"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Active Network Type"
        android:layout_below="@id/tv"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.ActionBar;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.net.ConnectivityManager;


public class MainActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the widgets reference from XML layout
        final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
        final Button btn = (Button) findViewById(R.id.btn);
        final TextView tv = (TextView) findViewById(R.id.tv);

        final ActionBar ab = getActionBar();
        ab.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FF99C5FF")));

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String type = getConnectionType();
                if(type!= null){
                    tv.setText("Active network type : " + type );
                }
                else {
                    tv.setText("No active network found.");
                }
           }
        });
    }

    // Custom method to detect active network connection type
    public String getConnectionType(){
        String type = null;
        /*
            ConnectivityManager
                Class that answers queries about the state of network connectivity. It also
                notifies applications when network connectivity changes. Get an instance of this
                class by calling Context.getSystemService(Context.CONNECTIVITY_SERVICE).
        */
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        /*
            NetworkInfo
                Describes the status of a network interface.

                Use getActiveNetworkInfo() to get an instance that represents the
                current network connection.
        */
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();

        // Determine if there is any active network
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if(isConnected) // If there is an active network
        {
            /*
                public String getTypeName ()
                    Return a human-readable name describe the type of the network,
                     for example "WIFI" or "MOBILE".

                Returns
                    the name of the network type
            */

            /*
                You can get active network type instead type name by using the following method.
                But you need to make the necessary changes on this code.
            */

            /*
                public int getType ()
                    Reports the type of network to which the info in this NetworkInfo pertains.

                Returns
                    one of TYPE_MOBILE, TYPE_WIFI, TYPE_WIMAX, TYPE_ETHERNET, TYPE_BLUETOOTH,
                    or other types defined by ConnectivityManager
            */
            type = activeNetwork.getTypeName();
        }
        return type;
    }
}
AndroidManifest.xml (permission)

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