سؤال

I need to communicate over htttp or https from an android, and I need a settings for my app "wifi only". It's a restriction for the communication. How to implement such a thing? I cannot find any information on AndroidHttpClient works only with Wifi - or 3G as well, and how to restrict it.

هل كانت مفيدة؟

المحلول

This code will check for wifi connection.

 public static boolean hasWIFIConnection(Context context)
                    {
                        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

                        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                        if (wifiNetwork != null && wifiNetwork.isConnected())
                            {
                                return true;
                            }
return false;

        }

نصائح أخرى

I've heard about the setNetworkPreference(int preference) method in the ConnectivityManager service. Although it is poorly documented, it appears this method can be used with integer constants which represents a network type.

You can find references to such constants in the ConnectivityManager class :

I would start digging this way.

EDIT :

You will need to be granted the folowing permissions :

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

try like this

ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) 
{
    if (ni.getTypeName().equalsIgnoreCase("WIFI"))
        if (ni.isConnected())
            haveConnectedWifi = true;
    if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
        if (ni.isConnected())
            haveConnectedMobile = true;}

starting from 23 getNetworkInfo is deprecated, use getActiveNetworkInfo

    public boolean hasWIFIConnection()
{
    ConnectivityManager connMgr = (ConnectivityManager) ContextProvider.getInstance().getApplication().getSystemService(Activity.CONNECTIVITY_SERVICE);

    NetworkInfo activeNetwork = connMgr.getActiveNetworkInfo();
    if (activeNetwork != null && (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI) && activeNetwork.isConnected())
    {
        return true;
    }
    return false;

}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top