【发布时间】:2010-11-28 01:34:53
【问题描述】:
我的问题可能既简单又尴尬,但我有点卡住了。
我有一个 Main.java 类,它扩展了 Activity。
在该类中,我执行以下操作:
ringerServer = new Thread(new RingerServer());
ringerServer.start();
我想做的是让 RingerServer 线程持续运行。
在那个线程中,我监听一个 TCP 连接。如果我得到一个,我开始另一个类,它发送和接收 UDP 数据包。
public class RingerServer implements Runnable {
public static final int SERVERPORT = 4445; // Default port to connect to
@Override
public void run() {
try {
// Create a socket for handling incoming requests
ServerSocket server = new ServerSocket(SERVERPORT);
while (!VoIPCall.onCall) {
// Wait for an incoming connection
Socket clientSocket = server.accept();
// TODO: Display a message for the user to accept or decline
// For now, automatically accept the call
Intent myIntent = new Intent(null, VoIPCall.class);
// Put the IP as a parameter
myIntent.putExtra("inetAddress", clientSocket.getInetAddress());
startActivity(myIntent);
}
} catch (IOException e) {
Log.e("TCP", "S: Error", e);
}
}
}
我的问题与线条有关:
Intent myIntent = new Intent(null, VoIPCall.class);
myIntent.putExtra("inetAddress", clientSocket.getInetAddress());
startActivity(myIntent);
这些行在 Activity 中可以正常工作,但它不会抱怨,因为它是一个线程,它不知道 Activity 类,因为它没有扩展它,而是实现了 Runnable。
我不确定如何让我的程序继续运行 RingerServer,但让主线程转到 VoIPCall 类。请问有什么想法吗?
非常感谢您的帮助。
非常感谢,
杰瑞
【问题讨论】:
-
代码中的一个问题是您将 null 作为上下文传递给 Intent。您需要向它传递一个实际的 Context 对象才能使该调用起作用。如果您希望您的 Thread 是一个单独的类,那么您可能应该创建一个以 Context 作为其参数的构造函数。您可以将正在实例化 Thread 的 Activity 或 Service 实例传入构造函数。
标签: android multithreading android-activity android-intent