0

此代码在 onCreate 中并从 txt 文件中读取 IP 地址:

DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpGet httppost = new HttpGet("http://readdeo.uw.hu/uploads/IP.txt");
HttpResponse response;

    response = httpclient.execute(httppost);

        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);

        InputStream is = buf.getContent();


        BufferedReader r = new BufferedReader(new InputStreamReader(is));

        StringBuilder total = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            total.append(line.trim());
        //    txv.setText(total);
        }} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

我怎样才能使它使用此字符串中的“总”StringBuilder 变量用于其他方法?

private static final String SERVER_IP = "IP_ADDRESS";
4

2 回答 2

0

您可以将 IP 地址添加为某个类中的字段,然后设置其值:

class YourClass {
    String mIpAddress;

    ...

    void yourMethod() {
        ...
        ipAddress = total;
    }
}

mIpAddress然后您应该考虑在初始化之前有人访问其他地方时会发生什么。

于 2013-08-10T23:55:00.217 回答
0

您可以通过处理程序解决此问题。

首先,您可以使用以下代码,例如

private int static final RESULT_IP_ADDRESS = 100;

Message msg = mHandler.obtainMessage(RESULT_IP_ADDRESS);
msg.getData().putString("IP_ADDRESS_KEY", total.toString());
msg.sendToTarget();

class MyHandler extends Handler{
    @override
    public void handleMessage(Message msg) {
        switch(msg.what) {
            case RESULT_IP_ADDRESS:
                String total = msg.getData().getString("IP_ADDRESS_KEY");
                // call your method with total data
                break;
            default:
                break;
        }
    }
}
于 2013-08-11T00:17:04.120 回答