sendMessage()未定义

时间:2016-07-19 13:05:30

标签: android handler android-handler

我正在尝试创建一个示例来了解Handlers的工作原理。如代码belwo所示,我创建了一个始终运行并增加变量i的workerThread。在...内 run()方法,我想将递增变量的值传递给TextView,如Handler类的主体所示。

问题是,“new Handler()”和“handler.sendMessage(m)”的行标有红色

请让我知道如何解决这个问题

MainActivity

public class MainActivity extends AppCompatActivity {

private final static String TAG = MainActivity.class.getClass().getSimpleName();
private TextView mtvIncr = null;

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

    this.mtvIncr = (TextView) findViewById(R.id.tvValue);
    new WorkerThread().start();
}

Handler handler =new Handler() {//ERROR
    @Override
    public void handleMessage(Message msg) {
        int sentInt = msg.getData().getInt("what");
        mtvIncr.setText("r:"+Integer.toString(sentInt));
    }
};

class WorkerThread extends Thread {

    private int i = 0;
    android.os.Handler mHandler = null;

    @Override
    public void run() {
        super.run();

        Looper.prepare();

        while(true) {
            Log.d(TAG, SubTag.bullet("WorkerThread", "i: " + (i++)));
            SystemClock.sleep(1000);

            Message m = new Message();
            Bundle b = new Bundle();
            b.putInt("what", i); // for example
            m.setData(b);
            handler.sendMessage(m);//ERROR
        }
    }
}
}

1 个答案:

答案 0 :(得分:0)

使用Message.obtain()获取Message对象

  

虽然Message的构造函数是公共的,但最好的方法是获取其中一个   这些是调用Message.obtain()或其中之一   Handler.obtainMessage()方法,它将从池中拉出它们   再生物。

并使用obj属性msg.obj = b;

  

obj:要发送给收件人的任意对象。

来自:

的信息

https://developer.android.com/reference/android/os/Message.html

示例:

Handler handler =new Handler() {
    @Override
    public void handleMessage(Message msg) {
        int sentInt = ((Bundle)msg.obj).getInt("what");
        mtvIncr.setText("r:"+Integer.toString(sentInt));
    }
};


class WorkerThread extends Thread {

    private int i = 0;
    android.os.Handler mHandler = null;

    @Override
    public void run() {
        super.run();

        Looper.prepare();

        while(true) {
            Log.d(TAG, SubTag.bullet("WorkerThread", "i: " + (i++)));
            SystemClock.sleep(1000);

            Message msg = Message.obtain();
            Bundle b = new Bundle();
            b.putInt("what", i); // for example
            msg.obj = b;
            handler.sendMessage(msg);
        }
    }
}