2010-11-28 74 views
0

我的問題可能會在同一時間變得簡單和尷尬,但我有點卡住了。Android:從線程調用活動

我有一個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類,因爲它沒有擴展它,但實現了Runnable。

我不知道如何讓我的程序繼續運行RingerServer,但主線程轉到VoIPCall類。請有任何想法嗎?

我真的很感謝你的幫助。

非常感謝你,

Jary

+0

您代碼中的一個問題是您將null作爲上下文傳遞給您的意圖。你需要傳遞一個實際的Context對象來使這個調用工作。如果你希望你的Thread成爲一個單獨的類,那麼你可能應該創建一個構造函數,它將Context作爲它的參數。您可以將實例化線程的Activity或Service實例傳入構造函數中。 – elevine 2010-11-28 16:00:52

回答

1

你應該將你的線程進入一個Service,而不是一個活動。我建議先閱讀Android開發者指南的Processes and Threads部分。然後查看Service的API文檔,這將幫助您開始創建一個。

+0

我已經讀過了線程和進程之間的區別,並開始閱讀服務,但它說:「服務不是一個線程,它不是一種方法來處理主線程(以避免應用程序不響應錯誤)「。我不明白爲什麼我的RingerServer應該移到一個服務,而不是因爲這個語句的線程。你能向我解釋一下推理嗎? – Jary 2010-11-28 02:23:01