Android 如何以编程方式设置 http 代理?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3629644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:04:06  来源:igfitidea点击:

How can you set the http proxy programmatically?

android

提问by Mike Ellery

I'm looking for a programmatic way to set-up http proxy settings for android handsets. I've tried using android.provider.Settings.System.putString() to set System.HTTP_PROXY, but my call fails (I'm using a 2.2 emulator image at the moment). My code looks like:

我正在寻找一种编程方式来为 android 手机设置 http 代理设置。我已经尝试使用 android.provider.Settings.System.putString() 来设置 System.HTTP_PROXY,但是我的调用失败了(我现在使用的是 2.2 模拟器映像)。我的代码看起来像:

if (System.putString(getContentResolver(), System.HTTP_PROXY, "10.10.2.1:8080")) {
    tv.append("put for HTTP_PROXY succeeded.\n");
}
else {
    tv.append("put for HTTP_PROXY failed.\n");
}

I've also added to my android manifest:

我还添加到我的 android 清单:

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

..although it's not clear from the docs which permission, if any, is required.

..虽然从文档中不清楚需要哪个权限(如果有)。

I'm familiar with this SO thread, but the technique there requires manual adb commands, which require the SDK tools and (possibly) a rooted phone.

我熟悉这个 SO thread,但是那里的技术需要手动 adb 命令,这需要 SDK 工具和(可能)有根电话。

Is there a way to accomplish this? Ideally, I'd like away to set an http proxy that will be used for both data and wifi connections.

有没有办法做到这一点?理想情况下,我想设置一个将用于数据和 wifi 连接的 http 代理。

回答by M Granja

It's not possible to do this as a 3rd-party app. You get this message:

作为第 3 方应用程序无法做到这一点。您收到此消息:

12-07 12:39:37.736: W/PackageManager(85): Not granting permission android.permission.WRITE_SECURE_SETTINGS to package com.mgranja.xxxxxxx (protectionLevel=3 flags=0xbe46)

Only apps that are signed with the same key as system apps can get this permission (i.e.: if you cook your own rom, you could add that funcionality)

只有使用与系统应用程序相同的密钥签名的应用程序才能获得此权限(即:如果您自己制作 rom,则可以添加该功能)

More info about permission levels on this question, specially adamk's answer.

有关此问题的权限级别的更多信息,特别是 adamk 的回答。

Why are these permissions being refused?

为什么这些权限会被拒绝?

回答by Jcs

If you are limiting the use of proxies to your own application you can use the Proxyand ProxySelectorAPI.

如果您将代理的使用限制在您自己的应用程序中,您可以使用ProxyProxySelectorAPI。

回答by Pawan Maheshwari

To set the proxy check Mike's answer; Following is code snippet to retrieve proxy details

设置代理检查迈克的答案;以下是检索代理详细信息的代码片段

public static String getProxyDetails(Context context) {
        String proxyAddress = new String();
        try {
            if (IsPreIcs()) {
                proxyAddress = android.net.Proxy.getHost(context);
                if (proxyAddress == null || proxyAddress.equals("")) {
                    return proxyAddress;
                }
                proxyAddress += ":" + android.net.Proxy.getPort(context);
            } else {
                proxyAddress = System.getProperty("http.proxyHost");
                proxyAddress += ":" + System.getProperty("http.proxyPort");
            }
        } catch (Exception ex) {
            //ignore
        }
        return proxyAddress;
    }

It'll return empty if some exception or no proxy detected;

如果检测到异常或未检测到代理,它将返回空;

回答by Prasanth Kumar S

You can set the proxy for your application VM, but due to security reasons, third party apps may not have the functionality to set device proxy.

您可以为应用虚拟机设置代理,但出于安全原因,第三方应用可能不具备设置设备代理的功能。

回答by John

I found something herethat looks like it might work

我在这里找到了一些看起来可能有用的东西

package com.BrowserSettings;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.provider.Settings;

public class BrowserSettingsUI extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        final Button button = (Button) findViewById(R.id.Button01);
        button.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                try {
                    Settings.System.putString(getContentResolver(),  
            Settings.System.HTTP_PROXY, "127.0.0.1:100");//enable proxy
                }catch (Exception ex){
                }
            }
        });

        final Button button2 = (Button) findViewById(R.id.Button02);
        button2.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                try {
                    Settings.System.putString(getContentResolver(), 
            Settings.System.HTTP_PROXY, "");//disable proxy
                }catch (Exception ex){
                }
            }
        });
    }
}

You must add

你必须添加

<uses-permission android:name=”android.permission.WRITE_SETTINGS” />

to your manifest.

到您的清单。

回答by lechuckcaptain

Did you try to call the com.android.settings.ProxySelectoractivity and let the user to enter the proxy? It's stored globally, but seems that it doesn't support the standard Proxy and ProxySelector API (for this problem there is already another question: How users/developers can set the Android's proxy configuration for versions 2.x?)

您是否尝试进行call the com.android.settings.ProxySelector活动并让用户进入代理?它是全局存储的,但似乎不支持标准的 Proxy 和 ProxySelector API(对于这个问题,已经有另一个问题:用户/开发人员如何为 2.x 版设置 Android 的代理配置?