Android Note ADB command application Example 1 (mobile phone with PC-side socket communication)

Source: Internet
Author: User
Tags getstream

Because I study Android also quite a long time, has kept the diary in Evernote, because just leave relatively idle plan to put Evernote in the log over and over again published to share online.

This article will use the C # and Java languages, respectively, to implement the PC client code that communicates with the Android terminal.

The ADB-related components are required to be referenced in the project by ADB and Android communication, respectively: Adb.exe,adbwinapi.dll,adbwinusbapi.dll.

Can be found under the Xxx\sdk\platform-tools directory

First look at the implementation of the C # language:

The interface effect is as follows:

namespace andusbclient{public partial class Form1:form {public const int WAITMS = 2000;        public const int TIMEOUT = 5000;        Private readonly TcpClient _tcpclient = new TcpClient ();        Private Boolean _flag = true;        Private Thread _thread;            Public Form1 () {InitializeComponent ();            Btnconnect.click + = Btnconnect_click;            formclosed + = new Formclosedeventhandler (form1_formclosed);            Btnsend.click + = Btnsend_click;        Btnclear.click + = Btnclear_click;                 private void Btnsend_click (object sender, EventArgs e) {if (_tcpclient.connected) {                var writer = new BinaryWriter (_tcpclient.getstream ());                String content = Rtxtcontent.text; try {byte[] bytes = new UTF8Encoding (false).                    GetBytes (content); Writer. Write (Int32tobytearray (bytes.                    Length)); Writer.                    Write (bytes); Writer.                    Flush ();                Setresult (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss") + "PC:" + content); } catch (Exception ex) {Console.WriteLine (ex.                Message); }}} private void Btnclear_click (object sender, EventArgs e) {Txtresult.text        = ""; private void Btnconnect_click (object sender, EventArgs e) {try {btn                connect.enabled = false; if (_thread! = null && _thread. IsAlive) {_thread.                    Abort ();                _thread = null;                    } _thread = new Thread (() = {outmsg (@ "Start connecting Android phone ...");                Doconnect ();                }); _thread.            Start ();                } catch (Exception ex) {Console.WriteLine (ex.            Message);        } btnconnect.enabled = true;        } private void Outmsg (String msg) {asyncaction (() = {lblinfo.text = msg;}); private void Setresult (String msg) {asyncaction () = {Txtresult.text + = @ "\ r \ n" + msg;}        ); public void Asyncaction (action action) {if (invokerequired) {Invoke                (New Action<action> (asyncaction), Action);            Return        } action ();  }//Connection public void Doconnect () {try {executecmd ("Kill-server",                0);                Executecmd ("Devices", 0); String strcmd = "Shell am broadcast-a notifyservicestop";                Use ADB shell AM broadcast command to send broadcast executecmd (strcmd, 0); Strcmd = "forward tcp:13333 tcp:10101";           Use ADB command to turn to Port Executecmd (strcmd, 0);     Strcmd = "Shell am broadcast-a notifyservicestart";                Executecmd (strcmd, 0);                IPAddress IPAddress = Ipaddress.parse ("127.0.0.1");                _tcpclient.connect (IPAddress, 13333);                Outmsg ("Connection succeeded!");                NetworkStream Networkkstream = _tcpclient.getstream ();                Networkkstream.readtimeout = TimeOut;                Networkkstream.writetimeout = TimeOut;                var reader = new BinaryReader (networkkstream);                var tempbuffer = new Byte[4]; IAsyncResult result = Networkkstream.beginread (tempbuffer, 0, Tempbuffer.                Length, NULL, tempbuffer);                _flag = true; while (_flag) {if (result. IsCompleted && _tcpclient.connected) {Tempbuffer = (byte[]) result.                        asyncstate;                        int length = ByteArrayToInt32 (Tempbuffer); var buffer = new Byte[length];                        int size = networkkstream.read (buffer, 0, length); if (Size > 0) {setresult (DateTime.Now.ToString ("Yyyy-mm-dd HH:mm:ss")                        ) + "Android:" + Encoding.UTF8.GetString (buffer, 0, size)); } result = Networkkstream.beginread (tempbuffer, 0, Tempbuffer.                    Length, NULL, tempbuffer);                } thread.sleep (200); }} catch (Exception ex) {Console.WriteLine (ex).            Message);            }} private static byte[] Int32tobytearray (Int32 m) {var arry = new Byte[4];            Arry[0] = (byte) (M & 0xFF);            ARRY[1] = (byte) ((M & 0xff00) >> 8);            ARRY[2] = (byte) ((M & 0xFF0000) >> 16);            ARRY[3] = (byte) ((M >>) & 0xFF); return arry;       } private static int ByteArrayToInt32 (byte[] bytes) {return Bitconverter.toint32 (bytes, 0        ); } private string Executecmd (String command, int seconds) {string output = ""; The output string if (!                String.IsNullOrEmpty (command)) {Console.WriteLine (command); var process = new process ();                Create Process object var startinfo = new ProcessStartInfo (); Startinfo.workingdirectory = Path.getdirectoryname (assembly.getexecutingassembly ().                Location); Startinfo.filename = "Adb.exe";                Set the command to be executed startinfo.verb = "runas"; startinfo.arguments = command; "/C" means exit Startinfo.useshellexecute = False immediately after executing the command; Do not use system shell to start Startinfo.redirectstandardinput = false; Do not redirect input startinfo.redirectstandardoutput = true; REDIRECT Output Startinfo.createnowindow = true; Do not create window process.                StartInfo = StartInfo; Console.WriteLine (Path.getdirectoryname (assembly.getexecutingassembly ().                Location)); try {if (process.                            Start ())//Begin process {if (seconds = = 0) { Process. WaitForExit (); Here the infinite waits for the process to end} else {proc Ess. WaitForExit (seconds); Wait for the process to end, wait time for the specified millisecond} output = process. Standardoutput.readtoend ();                    Output Console.WriteLine of the read process; }} catch (Exception ex) {Console.WriteLine (ex).                Message); } finally {process.                Close ();        }} return output; } public String Obj2json<t>(T data) {try {var json = new DataContractJsonSerializer (data).                GetType ()); using (var ms = new MemoryStream ()) {json.                    WriteObject (MS, data); Return Encoding.UTF8.GetString (Ms.                ToArray ());            }} catch (Exception ex) {throw ex; }} public Object Json2obj (string Strjson, Type t) {try {var j                son = new DataContractJsonSerializer (t); using (var ms = new MemoryStream (Encoding.UTF8.GetBytes (Strjson))) {return JSON.                ReadObject (MS);            }} catch (Exception ex) {throw ex; }} private void Form1_formclosed (object sender, Formclosedeventargs e) {_flag =            False     if (_tcpclient! = null)       {try {if (_tcpclient.connected) {                        NetworkStream stream = _tcpclient.getstream ();                        var writer = new BinaryWriter (stream); byte[] bytes = new UTF8Encoding (false).                        GetBytes ("EXIT"); Writer. Write (Int32tobytearray (bytes.                        Length)); Writer.                        Write (bytes); Writer.                        Flush (); Stream.                        Close (); Stream.                    Dispose (); }} catch (Exception ex) {Console.WriteLine (ex).                Message);                } finally {_tcpclient.close (); }            }        }    }}

  

Not to be continued.

Sufish

Source: http://www.cnblogs.com/dotnetframework/

This article is copyrighted by the author and the blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link. If you have questions, you can email: [Email protected] contact me, thank you very much.

Android Note ADB command application Example 1 (mobile phone with PC-side socket communication)

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.