简体   繁体   English

如何从特定线程发送udp数据报?

[英]How can I send udp datagrams from a specific thread?

I'm trying to send some udp datagrams which contain coded audio samples recorded via AudioRecord class. 我正在尝试发送一些udp数据报,其中包含通过AudioRecord类记录的编码音频样本。 This android class provides a notification when a certain period of recording is elapsed and its safe to consume recorded data. 当经过一定时间的记录并可以安全使用记录的数据时,此android类提供通知。

audioRecorder.setRecordPositionUpdateListener(new AudioRecord.OnRecordPositionUpdateListener() {

            @Override
            public void onPeriodicNotification(AudioRecord recorder) {
...

When the data are available I need to send them via udp like this: 当数据可用时,我需要像这样通过udp发送数据:

audioRecorder.setRecordPositionUpdateListener(new AudioRecord.OnRecordPositionUpdateListener() {

            @Override
            public void onPeriodicNotification(AudioRecord recorder) {

                byte[] pcm = new byte[320];
                recorder.read(pcm, 0, 320);

                mapPcm16bitLittleEndian2Float(pcm, 0, rawData, 0, 320/2);
                final byte encoded[]=encode(rawData);

                Thread t = new Thread(new Runnable() {
                    public void run() {
                        DatagramPacket p = new DatagramPacket(encoded, encoded.length, serverIPAddress, 5010);
                        try {
                            udpSocket.send(p);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    };
                });
                t.start();
            }

The problem is that the send method of the udpSocket can't be called on the UI thread otherwise an exception is thrown. 问题是不能在UI线程上调用udpSocket的send方法,否则会引发异常。 These notifications arrive once every 20ms, and I'd like to send the data through udp as soon as they're available but I think it's a waste of resources to create a new Thread every time. 这些通知每20毫秒发送一次,我想在数据可用时立即通过udp发送数据,但我认为每次创建一个新线程都浪费资源。 How can I manage to call the send method on a worker thread that I've previously created? 如何管理先前创建的工作线程上的send方法?

Create a secondary thread and post task to it using handler.Refer code below: 创建一个辅助线程并使用handler向其发布任务,请参考以下代码:

public class MainActivity extends Activity {
TextView txt;
// our handler
 Handler handler = new Handler() {
  @Override
  public void handleMessage(Message msg) {
//display each item in a single line
  txt.setText(txt.getText()+"Item "+System.getProperty("line.separator"));
     }
 };

 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  txt=(TextView)findViewById(R.id.txt);
 }

 @Override
 protected void onStart() {
  super.onStart();
              // create a new thread
  Thread background=new Thread(new Runnable() {

   @Override
   public void run() {
    for(int i=0;i<10;i++)
    {
     try {
      Thread.sleep(1000);        b.putString("My Key", "My Value: 

"+String.valueOf(i));
// send message to the handler with the current message handler          

handler.sendMessage(handler.obtainMessage());
     } catch (Exception e) {
      Log.v("Error", e.toString());
     }
    }
   }
  });

  background.start();
 }
}

refer this for more info 请参阅以获得更多信息

You can left only one Thread using BlockingQueue. 使用BlockingQueue只能保留一个线程。 Lock at this example. 锁定示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM