Android 監視案頭

來源:互聯網
上載者:User
一、由於在做“多屏互動”,在試各種解決方案;二、這個方法的大概思路為:

1、基於C/S模式,建立socket串連;

2、伺服器端,啟動線程,不斷截屏,並把映像流資訊寫到DataOutPutStream中;

3、用戶端,不停讀DataInPutStream,然後BitmapFactory.decodeByteArray,建立Bitmap,通知Handler更新試圖;

三、缺點:截屏,資訊流的讀寫過程很耗時。四、源碼

1、伺服器端源碼(PC)

Server.java:

public class Server {/** * 寫一個伺服器開啟的程式 * @param port:連接埠 */public void startServer (int port){try{//建立一個Serverc 對象   java.net.ServerSocket sc=new java.net.ServerSocket(port);    System.out.println("伺服器建立成功");   //開始不斷地接收資料   while (true){   //建立一個連接對象 java.net.Socket client=sc.accept(); UserThread ust=new UserThread(client); ust.init();             ust.start();   }   }catch(Exception ef){ef.printStackTrace();} }public static void main(String args[]){    Server cr=new Server();    cr.startServer(9090);}}

UserThread.java:

public class UserThread extends Thread {// 定義構造器,傳入對clientprivate java.net.Socket client;private java.io.InputStream ins;private java.io.OutputStream ous;public UserThread(java.net.Socket client) {this.client = client;}// 初始化public void init() {try {ins = client.getInputStream();ous = client.getOutputStream();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}// 寫run方法public void run() {try {sendImg();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}public void sendImg() throws Exception {DataOutputStream dous = new DataOutputStream(ous);Robot ro = new Robot();Dimension scrSize = Toolkit.getDefaultToolkit().getScreenSize();Rectangle r = new Rectangle(scrSize.width, scrSize.height);System.out.println("大小是:" + scrSize.height + " " + scrSize.width);while (true) {BufferedImage bui = ro.createScreenCapture(r);ByteArrayOutputStream imageStream = new ByteArrayOutputStream();boolean resultWrite = ImageIO.write(bui, "jpg", imageStream);byte[] tagInfo = imageStream.toByteArray();//System.out.println(tagInfo.length);//System.out.println(tagInfo[0] + " " + tagInfo[1]);//Image img = Toolkit.getDefaultToolkit().createImage(tagInfo, 0,//tagInfo.length);dous.writeInt(tagInfo.length + 5);dous.writeByte((byte) 4);dous.write(tagInfo);//Thread.sleep(100);}}}

2、用戶端(Android)

DeskShowActivity.java:

public class DeskShowActivity extends Activity{ //定義各個streamprivate java.io.InputStream ins;private java.io.OutputStream ous;private java.io.DataInputStream dins;//定義各個組件private ImageView img;private TextView tvw;//定義一個Bitmap 用來存ImageView的每個圖private Bitmap bmm;//放接收到資料的數組    private byte[] data;//初始化public void init(String ip){try{System.out.println(ip);    java.net.Socket soc=new java.net.Socket(ip,9090);    ins=soc.getInputStream();    dins=new DataInputStream(ins);    ous=soc.getOutputStream();    System.out.println("建立成功!");}catch(Exception ef){ef.printStackTrace();}}//內部類,myHandlerclass MyHandler extends Handler{public MyHandler(){  }public MyHandler(Looper looper){super(looper);}   public void handleMessage(Message msg){      img.setImageBitmap((Bitmap)msg.obj);   }}//onCreatepublic void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.mainfunctionactivity);        //得到各個組件        img=(ImageView)findViewById(R.id.imgView);//        tvw=(TextView)findViewById(R.id.exitTextView);//        //        //textView 添加監聽器//        tvw.setOnClickListener(new OnClickListener(){ //public void onClick(View v) {//    System.exit(0);//}//        });                init("192.168.1.179");                Looper looper = Looper.myLooper();                 //此處甚至可以不需要設定Looper,因為 Handler預設就使用當前線程的Looper           final MyHandler  myhandler= new MyHandler(looper);           new Thread() {                    public void run() {                 while(true){              try{              data=new byte[dins.readInt()-5];              dins.readByte();              //注意,這裡要用readfully              dins.readFully(data);              //注意,這裡要回收bmm ,否則報錯              if (bmm!=null){              bmm.recycle();              }              bmm=BitmapFactory.decodeByteArray(data, 0, data.length);              System.out.println("decode after:"+System.currentTimeMillis());              //每一百ms 執行 (可調)           //Thread.sleep(100);           //建立一個Message對象,並把得到的天氣資訊賦值給Message對象                       Message message = Message.obtain();                       message.obj = (Bitmap)bmm;                     myhandler.sendMessage(message);             } catch (Exception e) {           // TODO Auto-generated catch block           e.printStackTrace();           }                                   }          }                        }.start();   }}

五、運行效果:





聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.