2012-07-11 63 views
1

我正在制作一个接收UDP消息的应用程序。我遇到的问题是显示Activity,因为它仅在收到UDP消息后才显示。在onCreate我有startUdp()它开始收听UDP消息,我认为这是问题。直到收到UDP数据包才会显示活动

有没有办法告诉Activity何时完成加载或我应该开始收听?

Activity代码:

public class UDPActivity extends Activity { 
    private TextView textView; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_UDP); 

     // Setup the UDP stuff 
     startUDP(); 

     System.out.println("Sent Response of "); 

     TextView rowLetter = (TextView) findViewById(R.id.rowLetter); 
     TextView seatNumber = (TextView) findViewById(R.id.seatNumber); 
     Button btnClose = (Button) findViewById(R.id.btnClose); 

     Intent i = getIntent(); 

     // Binding Click event to Button 
     btnClose.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View arg0) { 
       //Closing SecondScreen Activity 
       finish(); 
      } 
     }); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.activity_make_light, menu); 
     return true; 
    } 

    private static final int UDP_SERVER_PORT = 12345; 
    private static final int MAX_UDP_DATAGRAM_LEN = 1500; 

    private void startUDP() { 
     Log.d("UDP", "S: Connecting..."); 
     String lText; 
     byte[] lMsg = new byte[MAX_UDP_DATAGRAM_LEN]; 

     DatagramSocket ds = null; 
     while (true) { 
      try { 
       ds = new DatagramSocket(UDP_SERVER_PORT); 
       //disable timeout for testing 
       //ds.setSoTimeout(100000); 
       DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length); 
       Log.d("UDP", "S: Receiving..."); 

       ds.receive(dp); 
       lText = new String(lMsg, 0, dp.getLength()); 
       Log.i("UDP packet received", "S: Recieved '" + lText); 
       textView = (TextView) findViewById(R.id.text1); 

       textView.setText(lText); 
      } catch (SocketException e) { 
       e.printStackTrace(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } finally { 
       if (ds != null) { 
        ds.close(); 
       } 
      } 
     } 
    } 
} 
+0

为了澄清您的问题请发布代码! – pedr0 2012-07-11 15:59:09

+0

'startUdp()'块吗? – 2012-07-11 16:01:26

+0

您应该修复您的问题以获得更好的格式。但是,您可以使用Log命令查看代码已经存在的位置。 'Log.e(“UDP”,“+++ AFTER STARTUDP +++”);'在startUdp()调用之后,如果程序到达那行代码,它将出现在你的LogCat中。 – JuiCe 2012-07-11 16:06:06

回答

1

不要做UI线程上的网络,将其移动到作为的AsyncTask这样的东西。

1

那么,作为一个简单的解决方案,你可以在onResume()中调用startUdp()而不是'onCreate()`。

但是,如果它真的阻止了网络I/O,那么Android很可能会杀死你的应用程序,因为它阻塞了主线程(UI)。

您应该在单独的线程中运行UDP侦听器,或使用AsyncTask并使用处理程序将任何收到的UDP数据包数据传递到主线程以进行显示。

+0

干杯我刚刚在不同的线程中运行它 – 2012-07-13 09:55:04