Android-based remote video surveillance system (including source code)

Source: Internet
Author: User
Tags get ip

The basic process is that Android as the socket client will capture every frame of image data sent out, the PC as the server receives and displays each frame image for remote monitoring. The picture is as follows (later PC side added a camera function) ...

(PS. Just learn Android and Java soon a lot of things still do not understand, master if know which places can continue to optimize the words also please more guidance AH)

The system code is as follows:
One, Android mobile phone client
(1) Androidmanifest.xml file. Add camera and socket permissions, and set the activity that the program starts to perform,

<?xml version= "1.0" encoding= "Utf-8"? ><manifest xmlns:android= "http://schemas.android.com/apk/res/  Android "package=" Org.wanghai.CameraTest "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk Android:minsdkversion= "/> <!--grant the program permission to use the camera--<uses-permission android:name=" Android.per Mission. CAMERA "/> <uses-feature android:name=" Android.hardware.camera "/> <uses-feature android:name=" a Ndroid.hardware.camera.autofocus "/> <uses-permission android:name=" Android.permission.INTERNET "/> < Uses-permission android:name= "Android.permission.KILL_BACKGROUND_PROCESSES"/> <uses-permission android:name = "Android.permission.RESTART_PACKAGES"/> <application android:icon= "@drawable/ic_launcher" Android : label= "@string/app_name" > <activity android:name= ".          GetIP "android:screenorientation=" Landscape "  Android:label= "@string/app_name" > <intent-filter> <action android:name= "android.i Ntent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> < /intent-filter> </activity> <activity android:name= ". Cameratest "android:screenorientation=" Landscape "android:label=" @string/app_name "> < /activity> </application> </manifest>         (2) MAIN.XM L set Surfaceview for camera capture Image preview? <?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "/http Schemas.android.com/apk/res/android "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "Andro         id:orientation= "vertical" > <surfaceview android:id= "@+id/sview" android:layout_width= "Fill_parent" android:layout_height= "Fill_parent" Android:scaletypE= "Fitcenter"/> </LinearLayout>         (3) Login.xml login screen, For input server Ip?<?xml version= "1.0" encoding= "Utf-8"? ><tablelayout xmlns:android= "http://schemas.android.com/ Apk/res/android "android:id=" @+id/loginform "android:orientation=" vertical "Android:layout_width=" fil L_parent "android:layout_height=" fill_parent "> <TableRow> <textview Android:la Yout_width= "Fill_parent" android:layout_height= "wrap_content" android:text= "IP:" Android:textsize= "10 PT "/><!--Enter the user name text box--><edittext android:id=" @+id/ipedittext "android:layout_width=" Fill_par        Ent "android:layout_height=" wrap_content "android:digits=" 0123456789. " Android:hint= "Please fill in server IP" android:selectallonfocus= "true"/></tablerow> </TableLayout>
         (4) Getip.java get the server IP, start cameratest activity through intent,        IP information passed through bundles? public class GetIP extends Activity {String ipname = null;        @Override public void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);             Set Full screen requestwindowfeature (window.feature_no_title);        GetWindow (). SetFlags (Windowmanager.layoutparams.flag_fullscreen,windowmanager.layoutparams.flag_fullscreen);                            Setcontentview (R.layout.main);   Final Builder builder = new Alertdialog.builder (this);                          Defines a Alertdialog.builder object Builder.settitle ("Login Server dialog box"); Set the title of the dialog box//Load/res/layout/login.xml interface layout Tablelayout Logi                               Nform = (tablelayout) getlayoutinflater (). Inflate (r.layout.login, NULL); Final EditText Iptext = (EditText) loginform.fiNdviewbyid (R.id.ipedittext);                              Builder.setview (LoginForm);  Set the View object displayed by the dialog box//Set a login button for the dialog box Builder.setpositivebutton ("Login"//                                Set the listener for the button, new Onclicklistener () {@Override                                        public void OnClick (Dialoginterface dialog, int which) {//here to perform login processing                                        Ipname = Iptext.gettext (). toString (). Trim ();                                        Bundle data = new bundle ();                                                                               Data.putstring ("Ipname", ipname);                                        Intent Intent = new Intent (getip.this,cameratest.class);                                        Intent.putextras (data);                         StartActivity (Intent);       }                        });                        Set a Cancel button for the dialog box Builder.setnegativebutton ("Cancel", new Onclicklistener ()  {@Override public void OnClick (dialoginterface                                        dialog, int which) {//Cancel login, don't do anything.                                System.exit (1);                }                        });        Create and display the dialog box Builder.create (). Show (); }}         (5) Cameratest.java program body. After setting previewcallback, the Onpreviewframe function of Previewcallback is called whenever a frame of image data is completed.        Here we convert YUV format data to JPG and enable threads to send data through the socket. public class Cameratest extends Activity {Surfaceview sview;        Surfaceholder Surfaceholder;               int screenwidth, screenheight;                    Camera camera; Defines the camera Boolean used by the system Ispreview = false;         Whether to browse in private String ipname; @SuppressWarnings ("deprecation") @Override public void OnCreate (Bundle savedinstancestate) {Super.oncrea        Te (savedinstancestate);             Set Full screen requestwindowfeature (window.feature_no_title);        GetWindow (). SetFlags (Windowmanager.layoutparams.flag_fullscreen,windowmanager.layoutparams.flag_fullscreen);                 Setcontentview (R.layout.main);        Get IP address Intent Intent = Getintent ();        Bundle data = Intent.getextras ();                                         Ipname = data.getstring ("Ipname");                ScreenWidth = 640;                               ScreenHeight = 480;                  Sview = (Surfaceview) Findviewbyid (R.id.sview);                               Gets the interface Surfaceview component Surfaceholder = Sview.getholder ();       Get Surfaceview surfaceholder//Add a callback listener for Surfaceholder         Surfaceholder.addcallback (New Callback () {@Override public void Su                                                       Rfacechanged (surfaceholder holder, int format, int width,int height) {                                                                                       } @Override public void surfacecreated (Surfaceholder holder) {                                            Initcamera (); Open camera} @Override public void surfaced  Estroyed (Surfaceholder holder) {//If camera is not NULL, release webcam if (camera! = null) {if (Ispreview) Camera.stoppreview (                                        );                                        Camera.release ();                camera = null;                } system.exit (0);                }                               });                     Setting the Surfaceview itself does not maintain buffer surfaceholder.settype (surfaceholder.surface_type_push_buffers);                private void Initcamera () {if (!ispreview) {camera = Camera.open ();                                } if (camera! = null &&!ispreview) {try{                                                               Camera.parameters Parameters = Camera.getparameters ();    Parameters.setpreviewsize (ScreenWidth, screenheight);                    Sets the size of the preview photo Parameters.setpreviewfpsrange (20,30); 20~30 frames per second Parameters.setpictureformat (IMAGEFO Rmat.           NV21);                                         Format Picture                      Parameters.setpicturesize (ScreenWidth, screenheight);                      Set the size of the photo//camera.setparameters (parameters);                 android2.3.3 do not need this line code camera.setpreviewdisplay (Surfaceholder); Display the viewfinder camera.setpreviewcallback (new Streamit (ipname) via Surfaceview         ));                                   Set the callback class Camera.startpreview ();                                  Start preview camera.autofocus (null);                        AF} catch (Exception e) {e.printstacktrace ();                } Ispreview = true;        }}} class Streamit implements Camera.previewcallback {private String ipname; Public Streamit (String ipname){this.ipname = Ipname; } @Override public void Onpreviewframe (byte[] data, camera camera) {Size size = Camera.getparameter                 S (). Getpreviewsize (); try{//Call Image.compresstojpeg () to convert YUV format image data to jpg yuvimage image = new Yuvimage (data, IMAGEFO Rmat.             NV21, size.width, size.height, NULL);                if (image!=null) {Bytearrayoutputstream OutStream = new Bytearrayoutputstream ();                Image.compresstojpeg (New Rect (0, 0, Size.width, size.height), and OutStream);                Outstream.flush ();                Enable threads to send image data out of thread th = new MyThread (outstream,ipname);                          Th.start ();         }}catch (Exception ex) {LOG.E ("Sys", "Error:" +ex.getmessage ());        }}} class MyThread extends thread{private byte bytebuffer[] = new byte[1024];            Private OutputStream Outsocket;   Private Bytearrayoutputstream Myoutputstream;                 Private String Ipname;                Public MyThread (Bytearrayoutputstream myoutputstream,string ipname) {this.myoutputstream = Myoutputstream;        This.ipname = Ipname;                try {myoutputstream.close ();                } catch (IOException e) {e.printstacktrace (); }} public void Run () {try{//Send image data through socket socket Tempsocket = n            EW Socket (ipname, 6000);            Outsocket = Tempsocket.getoutputstream ();            Bytearrayinputstream InputStream = new Bytearrayinputstream (Myoutputstream.tobytearray ());            int amount;            while ((Amount = Inputstream.read (bytebuffer))! =-1) {outsocket.write (bytebuffer, 0, amount);            } myoutputstream.flush ();            Myoutputstream.close ();                          Tempsocket.close ();} catch (IOException e) {e.printstacktrace (); }}}         second, PC server-side Imageserver.java is used to display images, and can take pictures? public class         imageserver {public static serversocket SS = NULL;                 public static void Main (String args[]) throws ioexception{ss = new ServerSocket (6000);        Final ImageFrame frame = new ImageFrame (ss);        Frame.setdefaultcloseoperation (Jframe.exit_on_close);                Frame.setvisible (TRUE);            while (true) {frame.panel.getimage ();        Frame.repaint ();        }}}/** A frame with an image panel*/@SuppressWarnings ("Serial") class ImageFrame extends jframe{        public Imagepanel Panel;        Public JButton JB; Public ImageFrame (ServerSocket ss) {//Get-screen dimensions Toolkit kit = Toolki        T.getdefaulttoolkit ();        Dimension screensize = Kit.getscreensize (); int ScreenheiGht = Screensize.height;         int screenwidth = Screensize.width;        Center frame in Screen settitle ("Imagetest");        SetLocation ((screenwidth-default_width)/2, (Screenheight-default_height)/2);         SetSize (Default_width, default_height);        Add panel to Frame This.getcontentpane (). setlayout (NULL);        panel = new Imagepanel (ss);        Panel.setsize (640,480);        Panel.setlocation (0, 0);        Add (panel);        JB = new JButton ("Take photos");        Jb.setbounds (0,480,640,50);        Add (JB);        SaveImage saveaction = new SaveImage (ss);    Jb.addactionlistener (saveaction);    } public static final int default_width = 640; public static final int default_height = 560; }/** A panel that displays a tiled image*/@SuppressWarnings ("Serial") class Imagepanel extends JPanel {private S    Erversocket SS;    private image Image;              private InputStream ins; Public Imagepanel (ServerSocket ss) {THIS.SS = ss        } public void GetImage () throws ioexception{Socket s = this.ss.accept ();        SYSTEM.OUT.PRINTLN ("Connection succeeded!");                This.ins = S.getinputstream ();                This.image = imageio.read (INS);    This.ins.close ();           } public void Paintcomponent (Graphics g) {super.paintcomponent (g);        if (image = = null) return;    G.drawimage (image, 0, 0, NULL);        }} class SaveImage implements ActionListener {randomaccessfile inFile = null;        byte bytebuffer[] = new byte[1024];        InputStream ins;                 Private ServerSocket SS;        Public SaveImage (ServerSocket ss) {THIS.SS = SS; } public void actionperformed (ActionEvent event) {try {Socket s = ss.accept                        ();                                                 INS = S.getinputstream ();            The file selector opens in the current directory JFileChooser JFC = new JFileChooser (".");    Jfc.showsavedialog (New Javax.swing.JFrame ());                                 Gets the current selection file referenced by the files Savedfile = Jfc.getselectedfile ();                                        You have selected the file if (savedfile! = null) {///read the data of the file, you can read it in a fast way, try {                                InFile = new Randomaccessfile (savedfile, "RW");                                } catch (FileNotFoundException e) {e.printstacktrace ();            }} int amount;            while ((Amount = Ins.read (bytebuffer))! =-1) {infile.write (bytebuffer, 0, amount);            } infile.close ();            Ins.close ();            S.close (); Javax.swing.JOptionPane.showMessageDialog (New Javax.swing.JFrame (), "saved successfully", "Prompt!", javax.swing.JOptio                Npane.plain_message); } catch (IOException e) {e.printsTacktrace (); }        }}

Open source is as follows (Android I am using the 4.03 SDK, other versions please change it yourself.) Please note which line is commented out in Initcamera () below the 2.3.3 version)

Can only run successfully on the android4.04 system's mobile phone.

Android-based remote video surveillance system (including source code)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.