无法使用处理程序更改Textview

时间:2014-06-19 16:05:14

标签: java android

@Override
public void run() {
int ret = 0;
byte[] buffer = new byte[16384]; //ByteArray
int i;
while (ret >= 0) {
    try {
        ret = mInputStream.read(buffer);   
    } catch (IOException e) {
        break;
    }
    i = 0;
    while (i < ret) {
        int len = ret - i;
       if(len >=1){
           Message m = Message.obtain(mHandler);
           int value = (int) buffer[i];
           m.obj = new ValueMsg(value);
           mHandler.sendMessage(m);

这里我想我从缓冲区向mHandler发送字节。可以发送总价值吗?或者像字节的蓝牙字节?            } 1

    }

};

Handler mHandler = new Handler(){
    public void handleMessage(Message msg){
        ValueMsg t = (ValueMsg)msg.obj;                
        mTextView.setText(""+t.getReading()+" Value");
        }

}; 它不会改变textView我不明白为什么。

@Override
public void onDestroy() {
unregisterReceiver(mUsbReceiver);
super.onDestroy();
}
public class ValueMsg{
private int reading;

public ValueMsg(int reading){
    this.reading = reading;
}
public int getReading(){
    return reading;
}

是否总是必须为值写一个新类?

最后一个问题你能给我一本关于android和java或youtube网站的好书吗?:)

修改

Handler mHandler = new Handler(){
        public void handleMessage( Message msg){
             post (new Runnable() {
                public void run() {
                    ValueMsg t = (ValueMsg) msg.obj;
                    mTextView.setText(" Value");
                }
            }
        }
    };

1 个答案:

答案 0 :(得分:0)

更改

ValueMsg t = (ValueMsg)msg.obj;                
        mTextView.setText(""+t.getReading()+" Value");

 post(new Runnable() {
void run() {
 ValueMsg t = (ValueMsg)msg.obj;                
            mTextView.setText(""+t.getReading()+" Value");
});

使用您的处理程序将更改发布到UI线程