简体   繁体   中英

Allow switch to toggle only if internet connection is available

I have used a switch in my android code. If internet service is available then only allow toggle else show a toast message. How do I achieve this? I am unable to do so using

switch.setOnCheckedChangeListener() .

The check is working only if I press the switch button twice.

aSwitch.setEnabled(false); 

works only after I click once

First create a boolean that carries a flag :

boolean checkInternetFlag = false;

Then create a method that check if internet is available like this for example:

public final boolean isInternetOn() {
  ConnectivityManager connectivityManager 
        = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
  NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
  return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

You will also need to add this permission in your manifest :

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

Then you can do what you want in a condition like this :

        checkInternetFlag = isInternetOn();
    if (!checkInternetFlag) {
        Toast.makeText(getActivity(), "Internet not available", Toast.LENGTH_LONG).show();
    }

Also you can disable your toggle switch like this :

aSwitch.setEnabled(false);

And to make switch not clickable use :

aSwitch.setClickable(false);

The following method will catch if there is a change occured to networkstate:

1)Add this code to onCreate():

  IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
  NetworkChangeReceiver receiver = new NetworkChangeReceiver();
  registerReceiver(receiver, filter);

2) Add OnDestroy() Method:

 @Override
 protected void onDestroy() {
  Log.v(LOG_TAG, "onDestory");
  super.onDestroy();

  unregisterReceiver(receiver);

 }

3) Add the Following Code to your activity:

public class NetworkChangeReceiver extends BroadcastReceiver
    {

    @Override
    public void onReceive(final Context context, final Intent intent)
    {

        Log.v(LOG_TAG, "Receieved notification about network status");
        isNetworkAvailable(context);

    }


    private boolean isNetworkAvailable(Context context)
    {
        ConnectivityManager connectivity = (ConnectivityManager)
                                           context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null)
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null)
            {
                for (int i = 0; i < info.length; i++)
                {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        if(!isConnected)
                        {
                            Log.v(LOG_TAG, "Now you are connected to Internet!");
                            aSwitch.setEnabled(true);
                            isConnected = true;
                        }
                        return true;
                    }
                }
            }
        }
        Toast.makeText(YourActivity.this, "Internet is not available", Toast.LENGTH_SHORT).show();
        aSwitch.setEnabled(false);
        isConnected = false;
        return false;
        }
    }

4)Add this permission in your manifest file :

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

Hopefully this relates to your requirement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM