Android: Calling an activity from a Thread
My problem is probably going to be simple and awkward at the same time, but I am a little stuck.
I have a Main.java class, that extends Activity.
Inside that class, I do the following:
ringerServer = new Thread(new RingerServer());
ringerServer.start();
What I want to do is have t开发者_如何转开发he RingerServer thread running continously.
Inside that thread, I listen for a TCP connection. If I get one, I start another class, which sends and receives UDP packet.
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);
}
}
}
My problem has to do with the lines:
Intent myIntent = new Intent(null, VoIPCall.class);
myIntent.putExtra("inetAddress", clientSocket.getInetAddress());
startActivity(myIntent);
Those lines would work fine inside an Activity but it doesn't to complain as it is a Thread, it doesn't know about the Activity class, because it doesn't extend it, but implements Runnable.
I am not sure how I can make my program keep running the RingerServer but have the main thread go to VoIPCall class. Any ideas please?
I really appreciate your help.
Thank you very much,
Jary
You should move your thread into a Service rather than an Activity. I recommend starting off by reading the Processes and Threads section of the Android Dev Guide. Then checkout the API docs for Service, which will help you get started creating one.
精彩评论