Friday, January 22, 2016

android - How to enable disable wifi service programmatically

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<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="#cfd4ca"
    >
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="40sp"
        android:padding="25sp"
        android:fontFamily="sans-serif-condensed"
        android:textStyle="bold"
        />
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/tv"
        android:text="Switch Between Wifi Service State"
        />
</RelativeLayout>
MainActivity.java

package com.cfsuman.me.androidcodesnippets;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.wifi.WifiManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private Context mContext;
    private Activity mActivity;

    private RelativeLayout mRelativeLayout;
    private TextView mTextView;
    private Button mButton;

    private WifiManager mWifiManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // Request window feature action bar
        requestWindowFeature(Window.FEATURE_ACTION_BAR);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Get the application context
        mContext = getApplicationContext();
        // Get the activity
        mActivity = MainActivity.this;

        /*
            WifiManager
                This class provides the primary API for managing all aspects of Wi-Fi connectivity.
                Get an instance of this class by calling Context.getSystemService(Context.WIFI_SERVICE).
                It deals with several categories of items:

                    The list of configured networks. The list can be viewed and updated, and
                    attributes of individual entries can be modified.

                    The currently active Wi-Fi network, if any. Connectivity can be established or
                    turn down, and dynamic information about the state of the network can be queried.

                    Results of access point scans, containing enough information to make decisions
                    about what access point to connect to.

                    It defines the names of various Intent actions that are broadcast upon any sort
                    of change in Wi-Fi state.

                This is the API to use when performing Wi-Fi specific operations. To perform operations
                that pertain to network connectivity at an abstract level, use ConnectivityManager.
        */
        // Get an instance of WifiManager
        mWifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

        // Change the action bar color
        getSupportActionBar().setBackgroundDrawable(
                new ColorDrawable(Color.parseColor("#FFFF0000"))
        );

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

        // Set a click listener for button widget
        mButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check the wifi status
                if(isWifiOn()){
                    /*
                        public boolean setWifiEnabled (boolean enabled)
                            Enable or disable Wi-Fi.

                        Parameters
                            enabled true to enable, false to disable.
                        Returns
                            true : if the operation succeeds (or if the existing state is the
                            same as the requested state).
                    */
                    // If wifi is on then off it
                    mWifiManager.setWifiEnabled(false);
                    designWifiOffState();
                }else {
                    // If wifi is disabled then enable it
                    mWifiManager.setWifiEnabled(true);
                    designWifiOnState();
                }
            }
        });
    }

    // Custom method to check wifi enable disable state
    protected boolean isWifiOn(){
        /*
            public boolean isWifiEnabled ()
                Return whether Wi-Fi is enabled or disabled.
            Returns
                true if Wi-Fi is enabled
        */
        return mWifiManager.isWifiEnabled();
    }

    // Custom method to design wifi service enable state
    protected void designWifiOnState(){
        mTextView.setText("Wifi Service Is Enabled.");
        mTextView.setTextColor(Color.BLUE);
        mButton.setText("Disable Wifi Service");
    }

    // Custom method to design wifi service disable state
    protected void designWifiOffState(){
        mTextView.setText("Wifi Service Is Disabled.");
        mTextView.setTextColor(Color.RED);
        mButton.setText("Enable Wifi Service");
    }
}
AnidroidManifest.xml [Permission]

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