看雪论坛作者ID:卓桐
public WifiConfigController(
WifiConfigUiBase parent, View view, AccessPoint accessPoint, boolean edit) {
...
WifiInfo info = mAccessPoint.getInfo();
if (info != null && info.getLinkSpeed() != -1) {
addRow(group, R.string.wifi_speed, info.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS);
}
addRow(group, R.string.wifi_security, mAccessPoint.getSecurityString(false));
boolean showAdvancedFields = false;
if (mAccessPoint.networkId != INVALID_NETWORK_ID) {
WifiConfiguration config = mAccessPoint.getConfig();
if (config.ipAssignment == IpAssignment.STATIC) {
mIpSettingsSpinner.setSelection(STATIC_IP);
showAdvancedFields = true;
} else {
mIpSettingsSpinner.setSelection(DHCP);
}
for(InetAddress a : config.linkProperties.getAddresses()) {
addRow(group, R.string.wifi_ip_address, a.getHostAddress());
}
if (config.proxySettings == ProxySettings.STATIC) {
mProxySettingsSpinner.setSelection(PROXY_STATIC);
showAdvancedFields = true;
} else if (config.proxySettings == ProxySettings.PAC) {
mProxySettingsSpinner.setVisibility(View.GONE);
TextView textView = (TextView)mView.findViewById(R.id.proxy_pac_info);
textView.setVisibility(View.VISIBLE);
textView.setText(context.getString(R.string.proxy_url) +
config.linkProperties.getHttpProxy().getPacFileUrl());
showAdvancedFields = true;
} else {
mProxySettingsSpinner.setSelection(PROXY_NONE);
}
}
...
private void showProxyFields() {
WifiConfiguration config = null;
mView.findViewById(R.id.proxy_settings_fields).setVisibility(View.VISIBLE);
if (mAccessPoint != null && mAccessPoint.networkId != INVALID_NETWORK_ID) {
config = mAccessPoint.getConfig();
}
if (mProxySettingsSpinner.getSelectedItemPosition() == PROXY_STATIC) {
mView.findViewById(R.id.proxy_warning_limited_support).setVisibility(View.VISIBLE);
mView.findViewById(R.id.proxy_fields).setVisibility(View.VISIBLE);
if (mProxyHostView == null) {
mProxyHostView = (TextView) mView.findViewById(R.id.proxy_hostname);
mProxyHostView.addTextChangedListener(this);
mProxyPortView = (TextView) mView.findViewById(R.id.proxy_port);
mProxyPortView.addTextChangedListener(this);
mProxyExclusionListView = (TextView) mView.findViewById(R.id.proxy_exclusionlist);
mProxyExclusionListView.addTextChangedListener(this);
}
if (config != null) {
ProxyProperties proxyProperties = config.linkProperties.getHttpProxy();
if (proxyProperties != null) {
mProxyHostView.setText(proxyProperties.getHost());
mProxyPortView.setText(Integer.toString(proxyProperties.getPort()));
mProxyExclusionListView.setText(proxyProperties.getExclusionList());
}
}
} else {
mView.findViewById(R.id.proxy_warning_limited_support).setVisibility(View.GONE);
mView.findViewById(R.id.proxy_fields).setVisibility(View.GONE);
}
}
private boolean ipAndProxyFieldsAreValid() {
mLinkProperties.clear();
mIpAssignment = (mIpSettingsSpinner != null &&
mIpSettingsSpinner.getSelectedItemPosition() == STATIC_IP) ?
IpAssignment.STATIC : IpAssignment.DHCP;
if (mIpAssignment == IpAssignment.STATIC) {
int result = validateIpConfigFields(mLinkProperties);
if (result != 0) {
return false;
}
}
mProxySettings = (mProxySettingsSpinner != null &&
mProxySettingsSpinner.getSelectedItemPosition() == PROXY_STATIC) ?
ProxySettings.STATIC : ProxySettings.NONE;
if (mProxySettings == ProxySettings.STATIC && mProxyHostView != null) {
String host = mProxyHostView.getText().toString();
String portStr = mProxyPortView.getText().toString();
String exclusionList = mProxyExclusionListView.getText().toString();
int port = 0;
int result = 0;
try {
port = Integer.parseInt(portStr);
result = ProxySelector.validate(host, portStr, exclusionList);
} catch (NumberFormatException e) {
result = R.string.proxy_error_invalid_port;
}
if (result == 0) {
ProxyProperties proxyProperties= new ProxyProperties(host, port, exclusionList);
mLinkProperties.setHttpProxy(proxyProperties);
} else {
return false;
}
}
return true;
}
public void setHttpProxy(ProxyProperties proxy) {
mHttpProxy = proxy;
}
public ProxyProperties getHttpProxy() {
return mHttpProxy;
}
void submit(WifiConfigController configController) {
final WifiConfiguration config = configController.getConfig();
if (config == null) {
if (mSelectedAccessPoint != null
&& mSelectedAccessPoint.networkId != INVALID_NETWORK_ID) {
mWifiManager.connect(mSelectedAccessPoint.networkId,
mConnectListener);
}
} else if (config.networkId != INVALID_NETWORK_ID) {
if (mSelectedAccessPoint != null) {
mWifiManager.save(config, mSaveListener);
}
} else {
if (configController.isEdit()) {
mWifiManager.save(config, mSaveListener);
} else {
mWifiManager.connect(config, mConnectListener);
}
}
if (mWifiManager.isWifiEnabled()) {
mScanner.resume();
}
updateAccessPoints();
}
public void save(WifiConfiguration config, ActionListener listener) {
if (config == null) throw new IllegalArgumentException("config cannot be null");
validateChannel();
sAsyncChannel.sendMessage(SAVE_NETWORK, 0, putListener(listener), config);
}
case WifiManager.CONNECT_NETWORK:
case WifiManager.SAVE_NETWORK: {
WifiConfiguration config = (WifiConfiguration) msg.obj;
int networkId = msg.arg1;
if (config != null && config.isValid()) {
if (config.proxySettings != ProxySettings.PAC) {
if (DBG) Slog.d(TAG, "Connect with config" + config);
mWifiStateMachine.sendMessage(Message.obtain(msg));
} else {
Slog.e(TAG, "ClientHandler.handleMessage cannot process msg with PAC");
if (msg.what == WifiManager.CONNECT_NETWORK) {
replyFailed(msg, WifiManager.CONNECT_NETWORK_FAILED);
} else {
replyFailed(msg, WifiManager.SAVE_NETWORK_FAILED);
}
}
} else if (config == null
&& networkId != WifiConfiguration.INVALID_NETWORK_ID) {
if (DBG) Slog.d(TAG, "Connect with networkId" + networkId);
mWifiStateMachine.sendMessage(Message.obtain(msg));
} else {
Slog.e(TAG, "ClientHandler.handleMessage ignoring invalid msg=" + msg);
if (msg.what == WifiManager.CONNECT_NETWORK) {
replyFailed(msg, WifiManager.CONNECT_NETWORK_FAILED);
} else {
replyFailed(msg, WifiManager.SAVE_NETWORK_FAILED);
}
}
break;
}
case WifiManager.SAVE_NETWORK:
config = (WifiConfiguration) message.obj;
NetworkUpdateResult result = mWifiConfigStore.saveNetwork(config);
if (result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID) {
replyToMessage(message, WifiManager.SAVE_NETWORK_SUCCEEDED);
} else {
loge("Failed to save network");
replyToMessage(message, WifiManager.SAVE_NETWORK_FAILED,
WifiManager.ERROR);
}
break;
NetworkUpdateResult saveNetwork(WifiConfiguration config) {
if (VDBG) localLog("saveNetwork", config.networkId);
if (config == null || (config.networkId == INVALID_NETWORK_ID &&
config.SSID == null)) {
return new NetworkUpdateResult(INVALID_NETWORK_ID);
}
boolean newNetwork = (config.networkId == INVALID_NETWORK_ID);
NetworkUpdateResult result = addOrUpdateNetworkNative(config);
int netId = result.getNetworkId();
if (newNetwork && netId != INVALID_NETWORK_ID) {
mWifiNative.enableNetwork(netId, false);
mConfiguredNetworks.get(netId).status = Status.ENABLED;
}
mWifiNative.saveConfig();
sendConfiguredNetworksChangedBroadcast(config, result.isNewNetwork() ?
WifiManager.CHANGE_REASON_ADDED : WifiManager.CHANGE_REASON_CONFIG_CHANGE);
return result;
}
private NetworkUpdateResult addOrUpdateNetworkNative(WifiConfiguration config) {
...
WifiConfiguration currentConfig = mConfiguredNetworks.get(netId);
if (currentConfig == null) {
currentConfig = new WifiConfiguration();
currentConfig.ipAssignment = IpAssignment.DHCP;
currentConfig.proxySettings = ProxySettings.NONE;
currentConfig.networkId = netId;
}
readNetworkVariables(currentConfig);
mConfiguredNetworks.put(netId, currentConfig);
mNetworkIds.put(configKey(currentConfig), netId);
NetworkUpdateResult result = writeIpAndProxyConfigurationsOnChange(currentConfig, config);
result.setIsNewNetwork(newNetwork);
result.setNetworkId(netId);
return result;
}
private class WifiStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
...
Message msg = mCsHandler.obtainMessage(EVENT_STATE_CHANGED,
new NetworkInfo(mNetworkInfo));
msg.sendToTarget();
} else if (intent.getAction().equals(WifiManager.LINK_CONFIGURATION_CHANGED_ACTION)) {
mLinkProperties = intent.getParcelableExtra(WifiManager.EXTRA_LINK_PROPERTIES);
Message msg = mCsHandler.obtainMessage(EVENT_CONFIGURATION_CHANGED, mNetworkInfo);
msg.sendToTarget();
}
}
}
private static class DefaultNetworkFactory implements NetworkFactory {
...
@Override
public NetworkStateTracker createTracker(int targetNetworkType, NetworkConfig config) {
switch (config.radio) {
case TYPE_WIFI:
return new WifiStateTracker(targetNetworkType, config.name);
...
}
}
}
try {
tracker = netFactory.createTracker(targetNetworkType, config);
mNetTrackers[targetNetworkType] = tracker;
} catch (IllegalArgumentException e) {
Slog.e(TAG, "Problem creating " + getNetworkTypeName(targetNetworkType)
+ " tracker: " + e);
continue;
}
tracker.startMonitoring(context, mTrackerHandler);
private class NetworkStateTrackerHandler extends Handler {
public NetworkStateTrackerHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
NetworkInfo info;
switch (msg.what) {
case NetworkStateTracker.EVENT_STATE_CHANGED: {
info = (NetworkInfo) msg.obj;
NetworkInfo.State state = info.getState();
...
} else if (state == NetworkInfo.State.CONNECTED) {
handleConnect(info);
}
if (mLockdownTracker != null) {
mLockdownTracker.onNetworkInfoChanged(info);
}
break;
}
case NetworkStateTracker.EVENT_CONFIGURATION_CHANGED: {
info = (NetworkInfo) msg.obj;
handleConnectivityChange(info.getType(), false);
break;
}
...
}
}
}
}
private void handleConnectivityChange(int netType, boolean doReset) {
...
if (mNetConfigs[netType].isDefault()) {
handleApplyDefaultProxy(newLp.getHttpProxy());
}
...
}
private void handleApplyDefaultProxy(ProxyProperties proxy) {
...
if (mGlobalProxy != null) return;
if (!mDefaultProxyDisabled) {
sendProxyBroadcast(proxy);
}
}
}
private void sendProxyBroadcast(ProxyProperties proxy) {
if (proxy == null) proxy = new ProxyProperties("", 0, "");
if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
if (DBG) log("sending Proxy Broadcast for " + proxy);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
mSettingsObserver.observe(mContext);
private static class SettingsObserver extends ContentObserver {
private int mWhat;
private Handler mHandler;
SettingsObserver(Handler handler, int what) {
super(handler);
mHandler = handler;
mWhat = what;
}
void observe(Context context) {
ContentResolver resolver = context.getContentResolver();
resolver.registerContentObserver(Settings.Global.getUriFor(
Settings.Global.HTTP_PROXY), false, this);
}
@Override
public void onChange(boolean selfChange) {
mHandler.obtainMessage(mWhat).sendToTarget();
}
}
case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
handleDeprecatedGlobalHttpProxy();
break;
}
private void handleDeprecatedGlobalHttpProxy() {
String proxy = Settings.Global.getString(mContext.getContentResolver(),
Settings.Global.HTTP_PROXY);
if (!TextUtils.isEmpty(proxy)) {
String data[] = proxy.split(":");
if (data.length == 0) {
return;
}
String proxyHost = data[0];
int proxyPort = 8080;
if (data.length > 1) {
try {
proxyPort = Integer.parseInt(data[1]);
} catch (NumberFormatException e) {
return;
}
}
ProxyProperties p = new ProxyProperties(data[0], proxyPort, "");
setGlobalProxy(p);
}
}
public void setGlobalProxy(ProxyProperties proxyProperties) {
enforceConnectivityInternalPermission();
synchronized (mProxyLock) {
if (proxyProperties == mGlobalProxy) return;
if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
String host = "";
int port = 0;
String exclList = "";
String pacFileUrl = "";
if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
!TextUtils.isEmpty(proxyProperties.getPacFileUrl()))) {
if (!proxyProperties.isValid()) {
if (DBG)
log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
return;
}
mGlobalProxy = new ProxyProperties(proxyProperties);
host = mGlobalProxy.getHost();
port = mGlobalProxy.getPort();
exclList = mGlobalProxy.getExclusionList();
if (proxyProperties.getPacFileUrl() != null) {
pacFileUrl = proxyProperties.getPacFileUrl();
}
} else {
mGlobalProxy = null;
}
ContentResolver res = mContext.getContentResolver();
final long token = Binder.clearCallingIdentity();
try {
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
exclList);
Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
} finally {
Binder.restoreCallingIdentity(token);
}
}
if (mGlobalProxy == null) {
proxyProperties = mDefaultProxy;
}
sendProxyBroadcast(proxyProperties);
}
private void sendProxyBroadcast(ProxyProperties proxy) {
if (proxy == null) proxy = new ProxyProperties("", 0, "");
if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
if (DBG) log("sending Proxy Broadcast for " + proxy);
Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
final long ident = Binder.clearCallingIdentity();
try {
mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void sendStickyBroadcastAsUser(Intent intent, UserHandle user) {
String resolvedType = intent.resolveTypeIfNeeded(getContentResolver());
try {
intent.prepareToLeaveProcess();
ActivityManagerNative.getDefault().broadcastIntent(
mMainThread.getApplicationThread(), intent, resolvedType, null,
Activity.RESULT_OK, null, null, null, AppOpsManager.OP_NONE, false, true, user.getIdentifier());
} catch (RemoteException e) {
}
}
public final int broadcastIntent(IApplicationThread caller,
Intent intent, String resolvedType, IIntentReceiver resultTo,
int resultCode, String resultData, Bundle map,
String requiredPermission, int appOp, boolean serialized, boolean sticky, int userId) {
enforceNotIsolatedCaller("broadcastIntent");
synchronized(this) {
intent = verifyBroadcastLocked(intent);
final ProcessRecord callerApp = getRecordForAppLocked(caller);
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
int res = broadcastIntentLocked(callerApp,
callerApp != null ? callerApp.info.packageName : null,
intent, resolvedType, resultTo,
resultCode, resultData, map, requiredPermission, appOp, serialized, sticky,
callingPid, callingUid, userId);
Binder.restoreCallingIdentity(origId);
return res;
}
}
private final int broadcastIntentLocked(ProcessRecord callerApp,
String callerPackage, Intent intent, String resolvedType,
IIntentReceiver resultTo, int resultCode, String resultData,
Bundle map, String requiredPermission, int appOp,
boolean ordered, boolean sticky, int callingPid, int callingUid,
int userId) {
...
if (Proxy.PROXY_CHANGE_ACTION.equals(intent.getAction())) {
ProxyProperties proxy = intent.getParcelableExtra("proxy");
mHandler.sendMessage(mHandler.obtainMessage(UPDATE_HTTP_PROXY_MSG, proxy));
}
...
}
case UPDATE_HTTP_PROXY_MSG: {
ProxyProperties proxy = (ProxyProperties)msg.obj;
String host = "";
String port = "";
String exclList = "";
String pacFileUrl = null;
if (proxy != null) {
host = proxy.getHost();
port = Integer.toString(proxy.getPort());
exclList = proxy.getExclusionList();
pacFileUrl = proxy.getPacFileUrl();
}
synchronized (ActivityManagerService.this) {
for (int i = mLruProcesses.size() - 1 ; i >= 0 ; i--) {
ProcessRecord r = mLruProcesses.get(i);
if (r.thread != null) {
try {
r.thread.setHttpProxy(host, port, exclList, pacFileUrl);
} catch (RemoteException ex) {
Slog.w(TAG, "Failed to update http proxy for: " +
r.info.processName);
}
}
}
}
} break;
public void setHttpProxy(String host, String port, String exclList, String pacFileUrl) {
Proxy.setHttpProxySystemProperty(host, port, exclList, pacFileUrl);
}
public static final void setHttpProxySystemProperty(String host, String port, String exclList,
String pacFileUrl) {
if (exclList != null) exclList = exclList.replace(",", "|");
if (false) Log.d(TAG, "setHttpProxySystemProperty :"+host+":"+port+" - "+exclList);
if (host != null) {
System.setProperty("http.proxyHost", host);
System.setProperty("https.proxyHost", host);
} else {
System.clearProperty("http.proxyHost");
System.clearProperty("https.proxyHost");
}
if (port != null) {
System.setProperty("http.proxyPort", port);
System.setProperty("https.proxyPort", port);
} else {
System.clearProperty("http.proxyPort");
System.clearProperty("https.proxyPort");
}
if (exclList != null) {
System.setProperty("http.nonProxyHosts", exclList);
System.setProperty("https.nonProxyHosts", exclList);
} else {
System.clearProperty("http.nonProxyHosts");
System.clearProperty("https.nonProxyHosts");
}
if (!TextUtils.isEmpty(pacFileUrl)) {
ProxySelector.setDefault(new PacProxySelector());
} else {
ProxySelector.setDefault(sDefaultProxySelector);
}
}
IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
if (b != null) {
IConnectivityManager service = IConnectivityManager.Stub.asInterface(b);
try {
ProxyProperties proxyProperties = service.getProxy();
Proxy.setHttpProxySystemProperty(proxyProperties);
} catch (RemoteException e) {}
}
public RouteSelector(Address address, URI uri, ProxySelector proxySelector, ConnectionPool pool,
Dns dns, RouteDatabase routeDatabase) {
this.address = address;
this.uri = uri;
this.proxySelector = proxySelector;
this.pool = pool;
this.dns = dns;
this.routeDatabase = routeDatabase;
this.postponedRoutes = new LinkedList<Route>();
resetNextProxy(uri, address.getProxy());
}
private void resetNextProxy(URI uri, Proxy proxy) {
this.hasNextProxy = true;
if (proxy != null) {
this.userSpecifiedProxy = proxy;
} else {
List<Proxy> proxyList = proxySelector.select(uri);
if (proxyList != null) {
this.proxySelectorProxies = proxyList.iterator();
}
}
}
private static ProxySelector defaultSelector = new ProxySelectorImpl();
@Override public List<Proxy> select(URI uri) {
return Collections.singletonList(selectOneProxy(uri));
}
private Proxy selectOneProxy(URI uri) {
if (uri == null) {
throw new IllegalArgumentException("uri == null");
}
String scheme = uri.getScheme();
if (scheme == null) {
throw new IllegalArgumentException("scheme == null");
}
int port = -1;
Proxy proxy = null;
String nonProxyHostsKey = null;
boolean httpProxyOkay = true;
if ("http".equalsIgnoreCase(scheme)) {
port = 80;
nonProxyHostsKey = "http.nonProxyHosts";
proxy = lookupProxy("http.proxyHost", "http.proxyPort", Proxy.Type.HTTP, port);
} else if ("https".equalsIgnoreCase(scheme)) {
port = 443;
nonProxyHostsKey = "https.nonProxyHosts";
proxy = lookupProxy("https.proxyHost", "https.proxyPort", Proxy.Type.HTTP, port);
} else if ("ftp".equalsIgnoreCase(scheme)) {
port = 80;
nonProxyHostsKey = "ftp.nonProxyHosts";
proxy = lookupProxy("ftp.proxyHost", "ftp.proxyPort", Proxy.Type.HTTP, port);
} else if ("socket".equalsIgnoreCase(scheme)) {
httpProxyOkay = false;
} else {
return Proxy.NO_PROXY;
}
if (nonProxyHostsKey != null
&& isNonProxyHost(uri.getHost(), System.getProperty(nonProxyHostsKey))) {
return Proxy.NO_PROXY;
}
if (proxy != null) {
return proxy;
}
if (httpProxyOkay) {
proxy = lookupProxy("proxyHost", "proxyPort", Proxy.Type.HTTP, port);
if (proxy != null) {
return proxy;
}
}
proxy = lookupProxy("socksProxyHost", "socksProxyPort", Proxy.Type.SOCKS, 1080);
if (proxy != null) {
return proxy;
}
return Proxy.NO_PROXY;
}
private Proxy lookupProxy(String hostKey, String portKey, Proxy.Type type, int defaultPort) {
String host = System.getProperty(hostKey);
if (host == null || host.isEmpty()) {
return null;
}
int port = getSystemPropertyInt(portKey, defaultPort);
return new Proxy(type, InetSocketAddress.createUnresolved(host, port));
}
private Proxy nextProxy() {
if (userSpecifiedProxy != null) {
hasNextProxy = false;
return userSpecifiedProxy;
}
if (proxySelectorProxies != null) {
while (proxySelectorProxies.hasNext()) {
Proxy candidate = proxySelectorProxies.next();
if (candidate.type() != Proxy.Type.DIRECT) {
return candidate;
}
}
}
hasNextProxy = false;
return Proxy.NO_PROXY;
}
private void resetNextInetSocketAddress(Proxy proxy) throws UnknownHostException {
socketAddresses = null;
String socketHost;
if (proxy.type() == Proxy.Type.DIRECT) {
socketHost = uri.getHost();
socketPort = getEffectivePort(uri);
} else {
SocketAddress proxyAddress = proxy.address();
if (!(proxyAddress instanceof InetSocketAddress)) {
throw new IllegalArgumentException(
"Proxy.address() is not an " + "InetSocketAddress: " + proxyAddress.getClass());
}
InetSocketAddress proxySocketAddress = (InetSocketAddress) proxyAddress;
socketHost = proxySocketAddress.getHostName();
socketPort = proxySocketAddress.getPort();
}
socketAddresses = dns.getAllByName(socketHost);
nextSocketAddressIndex = 0;
}
submit->
== save->
==== handleMessage->
====== sendMessage->
======== saveNetwork->
========== addOrUpdateNetworkNative->
============ writeIpAndProxyConfigurationsOnChange->
========== enableNetwork/saveConfig ->
…
handleConnectivityChange->接收处理LINK_CONFIGURATION_CHANGED_ACTION
handleConnect->接收处理NETWORK_STATE_CHANGED_ACTION
==== handleApplyDefaultProxy->
====== sendProxyBroadcast->
======== broadcastIntentLocked->
========== setHttpProxy->
============ setHttpProxySystemProperty->
handleBindApplication->
== getProxy->
==== setHttpProxySystemProperty->
====== setHttpProxySystemProperty->
SettingsObserver->
handleDeprecatedGlobalHttpProxy->
==setGlobalProxy->
====sendProxyBroadcast->
======broadcastIntentLocked->
========setHttpProxy->
==========setHttpProxySystemProperty->
handleBindApplication->
==getProxy->
====setHttpProxySystemProperty->
======setHttpProxySystemProperty->
…略过
RouteSelector->
==resetNextProxy->
====select->
======selectOneProxy->
========lookupProxy->
==========nextProxy->
============resetNextInetSocketAddress->
private WifiConfiguration getCurrentWifiConfiguration(WifiManager manager) {
if (manager == null || !manager.isWifiEnabled())
return null;
List<WifiConfiguration> configurationList = manager.getConfiguredNetworks();
WifiConfiguration configuration = null;
int networkId = manager.getConnectionInfo().getNetworkId();
for (int i = 0; i < configurationList.size(); ++i) {
WifiConfiguration wifiConfiguration = configurationList.get(i);
if (wifiConfiguration.networkId == networkId)
configuration = wifiConfiguration;
}
return configuration;
}
private boolean getWiFiProxySettings() {
WifiManager manager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration config = getCurrentWifiConfiguration(manager);
if (null == config)
return false;
try {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
ProxyInfo httpProxy = config.getHttpProxy();
Log.e("zhuo", "httpProxy="+httpProxy);
}
Object linkProperties = getField(config, "linkProperties");
if (null == linkProperties)
return false;
Class<?> proxyPropertiesClass = Class.forName("android.net.ProxyProperties");
Class<?> lpClass = Class.forName("android.net.LinkProperties");
Method getHttpProxy = lpClass.getDeclaredMethod("getHttpProxy");
getHttpProxy.setAccessible(true);
Object proxyProperties = getHttpProxy.invoke(linkProperties);
Log.e("zhuo", "proxyProperties="+proxyProperties);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
private boolean setWiFiProxySettings(String ip, int port) {
WifiManager manager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
WifiConfiguration config = getCurrentWifiConfiguration(manager);
if (null == config)
return false;
try {
Object linkProperties = getField(config, "linkProperties");
if (null == linkProperties)
return false;
Class<?> ProxyProperties = Class.forName("android.net.ProxyProperties");
Class<?> LinkProperties = Class.forName("android.net.LinkProperties");
Method setHttpProxy = LinkProperties.getDeclaredMethod("setHttpProxy", ProxyProperties);
setHttpProxy.setAccessible(true);
Constructor proxyPropertiesCtor = ProxyProperties.getConstructor(String.class, int.class, String.class);
Object proxySettings = proxyPropertiesCtor.newInstance(ip, port, null);
setHttpProxy.invoke(linkProperties, proxySettings);
setProxySettings("STATIC", config);
manager.updateNetwork(config);
manager.disconnect();
manager.reconnect();
Log.e("zhuo", "保存Proxy设置成功");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
private boolean execute(boolean readResponse) throws IOException {
try {
httpEngine.sendRequest();
if (readResponse) {
httpEngine.readResponse();
}
return true;
} catch (IOException e) {
if (handleFailure(e)) {
return false;
} else {
throw e;
}
}
}
private boolean handleFailure(IOException e) throws IOException {
RouteSelector routeSelector = httpEngine.routeSelector;
if (routeSelector != null && httpEngine.connection != null) {
routeSelector.connectFailed(httpEngine.connection, e);
}
OutputStream requestBody = httpEngine.getRequestBody();
boolean canRetryRequestBody = requestBody == null
|| requestBody instanceof RetryableOutputStream;
if (routeSelector == null && httpEngine.connection == null
|| routeSelector != null && !routeSelector.hasNext()
|| !isRecoverable(e)
|| !canRetryRequestBody) {
httpEngineFailure = e;
return false;
}
httpEngine.release(true);
RetryableOutputStream retryableOutputStream = (RetryableOutputStream) requestBody;
httpEngine = newHttpEngine(method, rawRequestHeaders, null, retryableOutputStream);
httpEngine.routeSelector = routeSelector;
return true;
}
public void connectFailed(Connection connection, IOException failure) {
Route failedRoute = connection.getRoute();
if (failedRoute.getProxy().type() != Proxy.Type.DIRECT && proxySelector != null) {
proxySelector.connectFailed(uri, failedRoute.getProxy().address(), failure);
}
routeDatabase.failed(failedRoute, failure);
}
public Connection next(String method) throws IOException {
for (Connection pooled; (pooled = pool.get(address)) != null; ) {
if (method.equals("GET") || pooled.isReadable()) return pooled;
pooled.close();
}
if (!hasNextTlsMode()) {
if (!hasNextInetSocketAddress()) {
if (!hasNextProxy()) {
if (!hasNextPostponed()) {
throw new NoSuchElementException();
}
return new Connection(nextPostponed());
}
lastProxy = nextProxy();
resetNextInetSocketAddress(lastProxy);
}
lastInetSocketAddress = nextInetSocketAddress();
resetNextTlsMode();
}
boolean modernTls = nextTlsMode() == TLS_MODE_MODERN;
Route route = new Route(address, lastProxy, lastInetSocketAddress, modernTls);
if (routeDatabase.shouldPostpone(route)) {
postponedRoutes.add(route);
return next(method);
}
return new Connection(route);
}
看雪ID:卓桐
https://bbs.pediy.com/user-670707.htm
推荐文章++++