我正在尝试将数据发送到名为 ToD1 的线程,该线程位于我的 Threads 类的内部类中,然后我需要对其进行一些工作,然后需要将其设置回 UI 线程处理程序我的问题是我将如何调用处理程序发送消息数据?我知道 AsyncTask 并将在以后尝试使用它。这个应用程序的目的是让我学习和理解 Handlers、HandlerThread 和 AsyncTask 的概念,以便我可以在我的编程中使用它们。
这是我的 MainActivity 代码:
public class MainActivity extends Activity implements OnClickListener {
TextView display1;
TextView display2;
EditText cl;
Button enter;
Button tod1;
Button tod2;
Bundle d = new Bundle();
static Handler mHandler;
Message msg;
Object task;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tod1 = (Button) findViewById(R.id.display1);
tod2 = (Button) findViewById(R.id.display2);
enter = (Button) findViewById(R.id.Enter);
display1 = (TextView) findViewById(R.id.Display1);
display2 = (TextView) findViewById(R.id.Display2);
cl = (EditText) findViewById(R.id.CL);
mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.Enter:
Bundle in = new Bundle();
String input = cl.getText().toString();
d.putString("in", input);
msg.setData(d);
// eclipes ask to resovle d1 varible type?
d1.sendMessage(msg);
notifyAll();
break;
case R.id.display1:
break;
case R.id.display2:
break;
}
}
}
这是我的线程类:
public class Threads {
public static class ToD1 {
Thread display1 = new Thread() {
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
Message msg = new Message();
Bundle b = new Bundle();
Looper.prepare();
Handler d1 = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
}
};
String output;
b.putString("key1", "out:" + String.valueOf(output));
msg.setData(b);
// Send msg to UI thread handler
// eclipes asked solve mHandler to varible type
mHandler.sendMessage(msg);
}
};
}
}