Android从c ++ socket接收图像

时间:2015-01-23 04:03:27

标签: java android c++ sockets

Android应用程序的新功能:需要一些帮助 我试图显示我从我的c ++套接字收到的图像。我能够从我的服务器套接字接收图像,它显示我收到的图像。但是之后仿真器力量关闭了,我不明白为什么。

Android代码

private  class Connect extends AsyncTask<Void, Void, Void>{
    @Override
    protected Void doInBackground(Void... params){
        int imageSize=921600;
        InputStream in;
        mRun = true;
        try{
            port1 = Integer.parseInt(port);
            client = new Socket(ip, port1);
            try{
                while(mRun){
                    in = client.getInputStream();
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    byte buffer[] = new byte[1024];
                    int remainingBytes = imageSize; //
                    while (remainingBytes > 0) {
                        int bytesRead = in.read(buffer);
                        if (bytesRead < 0) {
                            throw new IOException("Unexpected end of data");
                        }
                        baos.write(buffer, 0, bytesRead);
                        remainingBytes -= bytesRead;
                    }
                    in.close();
                    imageByte = baos.toByteArray();   
                    baos.close();
                    int nrOfPixels = imageByte.length / 3; // Three bytes per pixel.
                    int pixels[] = new int[nrOfPixels];
                    for(int i = 0; i < nrOfPixels; i++) {
                        int r = imageByte[3*i];
                        int g = imageByte[3*i + 1];
                        int b = imageByte[3*i + 2];

                        if (r < 0) 
                            r = r + 256; 

                        if (g < 0) 
                            g = g + 256;

                        if (b < 0) 
                            b = b + 256;

                        pixels[i] = Color.rgb(b,g,r);
                    }
                    Bitmap bitmap = Bitmap.createBitmap(pixels, 640, 480,Bitmap.Config.ARGB_8888);
                    camera.setImageBitmap(bitmap);
                    camera.invalidate();
                }
            } catch (IOException e){}
        }
        catch (UnknownHostException e) {}
        catch (IOException e){}
        return null;
    }
}

1 个答案:

答案 0 :(得分:0)

  

模拟器力量在此之后关闭,我不知道为什么

因为doInBackground方法在后台线程上运行,但您尝试在此处为doInBackground的图像设置位图:

camera.setImageBitmap(bitmap);
camera.invalidate();

要从主UI更新ImageView位图,请使用onPostExecute为ImageView调用setImageBitmapinvalidate,因为当doInBackground方法任务完成时,此方法在主UI线程上运行

使用runOnUiThread方法从setImageBitmap调用invalidatedoInBackground方法:

      YourActivityName.this.runOnUiThread(new Runnable() {

           @Override
           public void run() {
              camera.setImageBitmap(bitmap);
              camera.invalidate();
            }
      });