get Network Proxy - Android android.net

Android examples for android.net:ConnectivityManager

Description

get Network Proxy

Demo Code

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.Locale;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;

public class Main {

  @SuppressWarnings("deprecation")
  public static Proxy getProxy(Context context) {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

    NetworkInfo ni = cm.getActiveNetworkInfo();
    if (ni == null || !ni.isAvailable() || ni.getType() != ConnectivityManager.TYPE_MOBILE)
      return null;

    String imsi = getImsi(context);
    if (imsi != null && !imsi.equals("") && !imsi.startsWith("46001"))
      return null;

    String apn = ni.getExtraInfo().toLowerCase(Locale.CHINA);
    if (apn.contains("wap")) {
      String proxyHost = android.net.Proxy.getDefaultHost();
      int port = android.net.Proxy.getDefaultPort();
      if (proxyHost != null) {
        InetSocketAddress sa = new InetSocketAddress(proxyHost, port);
        return new Proxy(Proxy.Type.HTTP, sa);
      }//from  www . j  a  va2s .  c  o  m
    }
    return null;
  }

  public static String getImsi(Context context) {
    String imsi = null;
    TelephonyManager phoneManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
    if (phoneManager != null)
      imsi = phoneManager.getSubscriberId();
    if (imsi == null)
      imsi = "";
    return imsi;
  }

}

Related Tutorials