8

我正在尝试监视 android 上的网络连接。这不能在主线程上完成,因此数据收集发生在我生成的单独线程上 - 我正在学习使用 Handler 类每秒向 UI 报告。这是我的代码的相关片段......

public class MainActivity extends Activity {
    private TextView textView;
    private int linkSpeed;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Message message = msg;
            textView.setText(message);
            setContentView(textView);

        }
    };

    /** Called when the activity is created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {       
        super.onCreate(savedInstanceState);
        textView = new TextView(this);
        textView.setTextSize(25);

        Thread thread = new Thread() {
            public void run() {
                for (;;) {
                    try {
                        WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
                        while (true)
                        {
                            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
                            if (wifiInfo != null) {
                                linkSpeed = wifiInfo.getLinkSpeed(); //measured using WifiInfo.LINK_SPEED_UNITS
                            }
                            else {
                                linkSpeed = -1;
                            }

                    }
                        String message = "linkSpeed = " + linkSpeed;
                        handler.handleMessage(message);
                        Thread.sleep(1000);
                    }
                    catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        };

        thread.start();
    }

问题是,我从生成的新线程获得的消息是“String”类型的,但我似乎无法重载 Handler 类中的 handleMessage 方法来获取字符串而不是消息。我认为字符串和消息之间没有直接的转换,因为 Message 类中唯一返回字符串的方法是 toString() 方法,但它返回的是描述,而不是消息包含的内容。我也对如何将字符串转换为消息感到困惑——我觉得我正在做一个非常迂回的方法。任何帮助将不胜感激!

4

2 回答 2

21

You don't have to overload or try to do any coversions between String and Message. What you should do, is to put that String into an object of type Message and sent it to the Handler. Then in handleMessage() extract the String from the Message.

Something like this:

// ....
String message = "linkSpeed = " + linkSpeed;
Message msg = Message.obtain(); // Creates an new Message instance
msg.obj = message; // Put the string into Message, into "obj" field.
msg.setTarget(handler); // Set the Handler
msg.sendToTarget(); //Send the message
//....

And in handleMessage():

@Override
public void handleMessage(Message msg) {
    String message = (String) msg.obj; //Extract the string from the Message
    textView.setText(message);
    //....
}

But besides this, the program has an issue: you won't be able to send the data to the handler because that part of the code is unreachable:

while (true) {
    WifiInfo s = wifiManager.getConnectionInfo();
    //..
}
String message = "linkSpeed = " + linkSpeed; // This line never won't be reached.

Also, don't forget to stop the Thread at some time, otherwise it will continue to run even after the app is closed.

于 2013-06-28T20:42:42.970 回答
9

您可以使用 Bundle 将对象(如字符串)附加到 Message 对象。

我创建了这个例子:

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

public class MainActivity extends Activity {

    Handler handler = new Handler()
    {
        @Override
        public void handleMessage(Message msg) {
            Bundle bundle = msg.getData();

            String text = bundle.getString("key");

            // text will contain the string "your string message"
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Thread thread = new Thread()
        {
            @Override
            public void run() {
                Message message = handler.obtainMessage();

                Bundle bundle = new Bundle();
                bundle.putString("key", "your string message");

                message.setData(bundle);

                handler.sendMessage(message);
            }
        };

        thread.start();
    }
}
于 2013-06-28T20:40:22.023 回答