我有一个 MainActivity,它是创建 TCP 工作线程的默认启动 Activity。该 TCP 线程从服务器接收一些数据并将其传递给当前显示的 Activity,表示还有两个名为 Activity1 和 Activity2 的 Activity 将显示接收到的数据。
我如何使用 Handlers 实现这一点?这是我所拥有的概述......如果我完全错了,请提出解决方案或更改所有内容。
public class MainActivity extends Activity
{
public static TCPFunctions tcp = null;
public static Handler handler;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
handler = new Handler();
tcp = new TCPFunctions(this, handler);
tcp.start();
}
}
----------------------------------------TCP 线程类-------- --------------------------
public class TCPFunctions extends Thread
{
public Handler handler;
//socket and io streams are here and they work properly
Public TCPFunctions(MainActivity main, Handler _handler)
{
this.main = main;
handler = _handler;
}
public void run()
{
Intent showActivity1 = new Intent(main, Activity1.class);
main.startActivity(showActivity1);
while(true)
{
directories = new Vector<String>();
directories = (Vector<String>) inputStream.readObject();
Message msg = Message.obtain();
msg.obj = directories;
handler.sendMessage(msg);
directories = null;
}
}
}
现在说在 Activity1 我想要这个目录对象...可以说我的 Activity1 有一个按钮,按下该按钮时会向服务器发送请求以获取目录对象...由 TCP 线程接收...现在我该怎么做在 Activity1 中获取它并更新 UI ...
基本上,目录对象是字符串的 Vetor,我想在 Activity1/Activity2 中包含的 ListView 上显示字符串
public class Activity1 extends Activity implements OnClickListener,OnItemClickListener
{
private ListView directoryList;
private Button rootButton;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.fileexplorer);
directoryList = (ListView) findViewById(R.id.directories);
rootButton.setOnClickListener(this);
directoryList.setOnItemClickListener(this);
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.root_button:
Log.d(TAG, "FileExplorer: Root Button Pressed");
//request for directories made here
break;
}
}
// What should be the Handler code to get the directories ?
}