Android 从 C++ 套接字接收图像

Android receiving image from c++ socket

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;
    }
}

emulator force closes after that and i have no idea why

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

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

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

使用runOnUiThread方法从doInBackground调用setImageBitmapinvalidate方法:

      YourActivityName.this.runOnUiThread(new Runnable() {

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