Socket實現pc端與手機Android端圖片傳輸
阿新 • • 發佈:2019-01-28
package com.example.fdt.client; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.IOException; import java.net.Socket; import android.app.Activity; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView imageView = null; private Bitmap bmp = null; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView = (ImageView) findViewById(R.id.image01); Button btn = (Button) findViewById(R.id.button1); btn.setOnClickListener(new OnClickListener() { public void onClick(View v) { Thread t = new Thread() { @Override public void run() { super.run(); Socket s = null; try { s= new Socket("192.168.1.100", 9998); DataInputStream dataInput = new DataInputStream( socket.getInputStream()); int size = dataInput.readInt(); byte[] data = new byte[size]; int len = 0; while (len < size) { len += dataInput.read(data, len, size - len); } ByteArrayOutputStream out = new ByteArrayOutputStream(); bmp = BitmapFactory.decodeByteArray(data, 0, data.length); bmp.compress(CompressFormat.PNG, 100, out); myHandler.obtainMessage().sendToTarget(); } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }; t.start(); } }); } private Handler myHandler = new Handler(){ public void handleMessage(android.os.Message msg) { imageView.setImageBitmap(bmp); }; }; }