Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)

由于本人学习Android也挺长时间了,一直把日记记在evernote里面,由于刚离职比较空闲就打算把evernote里的日志一遍遍整理出来发布到网上分享。

Android端的代码:

布局文件:activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.androidusbserver.MainActivity" >

    <EditText
        android:id="@+id/etResult"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:inputType="textMultiLine"
        >
    </EditText>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <EditText
            android:id="@+id/etInput"
            android:layout_width="200dp"
            android:layout_height="wrap_content">
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Send" />
    </LinearLayout>

</LinearLayout>

定义广播接收者接收adb发送的命令:AdbBroadcastReceiver.java

public class AdbBroadcastReceiver extends BroadcastReceiver {

    private static final String TAG = "AdbBroadcastReceiver";

    private static final  String START_ACTION = "NotifyServiceStart";

    private static final  String STOP_ACTION = "NotifyServiceStop";

    @Override
    public void onReceive(Context context, Intent intent) {

        String threadName = Thread.currentThread().getName();

        String action = intent.getAction();

        Log.d(TAG, threadName + "-->>"
                + "AdbBroadcastReceiver onReceive START_ACTION:" + action);

        if (START_ACTION.equalsIgnoreCase(action)) {

            context.startService(new Intent(context, NetWorkService.class));

        } else if (STOP_ACTION.equalsIgnoreCase(action)) {

            context.stopService(new Intent(context, NetWorkService.class));

        }
    }
}

定义android socket服务端接收和发送socket:NetWorkService.java

public class NetWorkService extends Service {

    private static final String TAG = "NetWorkService";
    private static Boolean mainThreadFlag = true;
    private static Boolean ioThreadFlag = true;
    private ServerSocket serverSocket = null;
    private final int SERVER_PORT = 10101;// 端口号
    private List<Socket> sockets = new ArrayList<Socket>();
    private Handler _hander = null;

    @Override
    public IBinder onBind(Intent intent) {
        return new MsgSenderBinder();
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    private void doListen() {
        if (serverSocket != null) {
            try {
                serverSocket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            serverSocket = null;
        }
        try {
            serverSocket = new ServerSocket(SERVER_PORT);
            while (mainThreadFlag) {
                Socket socket = serverSocket.accept();
                sockets.add(socket);
                new Thread(new ThreadReadWriterSocket(socket)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("tt", "ConnectService-->>onStartCommand()");
        mainThreadFlag = true;
        if (serverSocket == null || serverSocket.isClosed()) {
            Thread t = new Thread() {
                public void run() {
                    doListen();
                };
            };
            t.start();
        }
        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mainThreadFlag = false;
        ioThreadFlag = false;
        Log.v(TAG, Thread.currentThread().getName()
                + "-->> onDestroy serverSocket.close()");
        try {
            for (Socket socket : sockets) {
                if (socket != null && !socket.isClosed()) {
                    socket.close();
                }
            }
            sockets.clear();
            if (serverSocket != null)
                serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class MsgSenderBinder extends Binder implements IMessage {
        @Override
        public void sendMsg(String msg) {
            if (sockets.size() > 0 && !TextUtils.isEmpty(msg)) {
                for (Socket socket : sockets) {
                    if (!socket.isClosed()) {
                        try {
                            BufferedOutputStream out = new BufferedOutputStream(
                                    socket.getOutputStream());
                            byte[] bytes = msg.trim().getBytes();
                            out.write(MyUtils.intToByte(bytes.length));
                            out.write(bytes);
                            out.flush();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }

        @Override
        public void receiveMsg(Handler hander) {
            _hander = hander;
        }
    }

    class ThreadReadWriterSocket implements Runnable {

        private Socket client;

        public ThreadReadWriterSocket(Socket client) {
            this.client = client;
        }

        @Override
        public void run() {
            Log.d(TAG, "a client has connected to server!");
            BufferedInputStream in;
            try {
                InputStream is = client.getInputStream();
                in = new BufferedInputStream(is);
                String currCMD = "";
                ioThreadFlag = true;
                while (ioThreadFlag) {
                    try {
                        if (client.isClosed()) {
                            break;
                        }
                        currCMD = readDataFromSocket(in);
                        if (_hander != null && !TextUtils.isEmpty(currCMD)) {
                            Message msg = new Message();
                            msg.what = 1;
                            msg.obj = currCMD.trim();
                            _hander.sendMessage(msg);
                        }
                        if (currCMD.trim().equalsIgnoreCase("exit")) {
                            ioThreadFlag = false;
                        }
                        Thread.sleep(200);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                in.close();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    sockets.remove(client);
                    if (client != null) {
                        Log.v(TAG, Thread.currentThread().getName() + "-->>"
                                + "client.close()");
                        client.close();
                    }
                } catch (IOException e) {
                    Log.e(TAG, Thread.currentThread().getName() + "-->>"
                            + "read write error");
                    e.printStackTrace();
                }
            }
        }

        public String readDataFromSocket(InputStream in) {
            String msg = "";
            byte[] tempbuffer = new byte[4];
            try {
                int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
                if (numReadedBytes <= 0)
                    return msg;
                int size = MyUtils.bytesToInt(tempbuffer);
                if (size > 0 && size <= 10000) {
                    byte[] buffer = new byte[size];
                    int length = in.read(buffer, 0, buffer.length);
                    if (length > 0) {
                        msg = new String(buffer, 0, length, "utf-8");
                        Log.v(TAG, Thread.currentThread().getName() + "-->>"
                                + "received data: " + msg);
                        buffer = null;
                    }
                }
            } catch (Exception e) {
                Log.v(TAG, Thread.currentThread().getName() + "-->>"
                        + "readFromSocket error");
                e.printStackTrace();
            }
            return msg;
        }
    }
}

MainActivity.java

public class MainActivity extends Activity implements OnClickListener {

    private EditText etResult;
    private EditText etInput;
    private Button btnSend;

    private MyConn conn;
    private IMessage iMsg = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        etResult = (EditText) findViewById(R.id.etResult);
        etInput = (EditText) findViewById(R.id.etInput);
        btnSend = (Button) findViewById(R.id.btnSend);
        btnSend.setOnClickListener(this);
        Intent intent = new Intent(this, NetWorkService.class);
        startService(intent);
        conn = new MyConn();
        bindService(intent, conn, BIND_AUTO_CREATE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.btnSend:
            sendMsg();
            break;
        }
    }

    @Override
    protected void onDestroy() {
        unbindService(conn);
        super.onDestroy();
    }

    private void sendMsg() {
        if (iMsg != null) {
            iMsg.sendMsg(etInput.getText().toString());
            etResult.setText(etResult.getText().toString() + "\r\n"
                    + "Android: " + etInput.getText().toString() + "\r\n");
        }
    }

    private static class MyHandler extends Handler {

        WeakReference<MainActivity> mActivity;

        MyHandler(MainActivity activity) {
            mActivity = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 1: {
                mActivity.get().etResult.setText(mActivity.get().etResult
                        .getText().toString()
                        + "\r\n"
                        + "PC: "
                        + msg.obj
                        + "\r\n");
            }
                break;
            default:
                break;
            }
        }
    }

    private MyHandler updateHandler = new MyHandler(this);

    private class MyConn implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            iMsg = (IMessage) service;
            iMsg.receiveMsg(updateHandler);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }
}

MyUtils.java

public class MyUtils {

    public static int bytesToInt(byte[] bytes) {
        int addr = bytes[0] & 0xFF;
        addr |= ((bytes[1] << 8) & 0xFF00);
        addr |= ((bytes[2] << 16) & 0xFF0000);
        addr |= ((bytes[3] << 25) & 0xFF000000);
        return addr;
    }

    public static byte[] intToByte(int i) {
        byte[] abyte0 = new byte[4];
        abyte0[0] = (byte) (0xff & i);
        abyte0[1] = (byte) ((0xff00 & i) >> 8);
        abyte0[2] = (byte) ((0xff0000 & i) >> 16);
        abyte0[3] = (byte) ((0xff000000 & i) >> 24);
        return abyte0;
    }
}

IMessage.java

public interface IMessage {

    void sendMsg(String msg);

    void receiveMsg(Handler hander);
}

AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidusbServer.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name=".AdbBroadcastReceiver" >
            <intent-filter>
                <action android:name="NotifyServiceStart" />
                <action android:name="NotifyServiceStop" />
            </intent-filter>
        </receiver>

        <service android:name=".NetWorkService" >
        </service>
    </application>

作者:sufish

出处:http://www.cnblogs.com/dotnetframework/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以邮件:[email protected]联系我,非常感谢。

时间: 2024-10-02 06:25:02

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)的相关文章

Android笔记之adb命令应用实例1(手机端与PC端socket通讯下)

由于本人学习Android也挺长时间了,一直把日记记在evernote里面,由于刚离职比较空闲就打算把evernote里的日志一遍遍整理出来发布到网上分享. 本篇将分别使用C#和java语言,来实现和android端通讯的PC客户端代码. 通过adb和Android通讯需要引用adb相关的组件到项目中,分别为:adb.exe,AdbWinApi.dll,AdbWinUsbApi.dll. 可以在XXX\sdk\platform-tools目录下找到 首先看C#语言的实现: 界面效果如下: nam

Android笔记之adb命令解析1

由于本人学习Android也挺长时间了,一直把日记记在evernote里面,由于刚离职比较空闲就打算把evernote里的日志一遍遍整理出来发布到网上分享. 要在cmd命令中直接使用adb,需要配置环境变量:目录XXX\sdk\platform-tools 查看adb -help 帮助命令打印出以下内容: Android Debug Bridge version 1.0.31 <!--安卓调试桥接器 版本号:1.0.31--> -a - directs adb to listen on all

Android开发中adb命令

作用: adb是SDK提供的一个常用的命令行工具,全称为Android Debug Bridge就是调试桥的作用,用于在调试时连接本机和手机设备. 借助这个工具,我们可以管理设备或手机模拟器的状态. 还可以进行以下的操作:  1.快速更新设备或手机模拟器中的代码,如应用或Android 系统升级: 2.在设备上运行shell命令: 3.管理设备或手机模拟器上的预定端口: 4.在设备或手机模拟器上复制或粘贴文件: 详解: 没开启一个Android 模拟器, 就相当于开启了一个新的单独系统,这个系统

Android开发执行adb 命令行命令

1.在Android开发中调用adb命令进行应用安装,将应用安装到 /system/app目录下 /** * install the app in use adb command,this style is silent * */ private void adbInstallTheAPP(){ //adb push core code String command = "cp" + "the android apk file path" + "/syst

Android 常用的adb命令

1.安装APK(如果加 -r 参数,保留已设定数据,重新安装filename.apk) adb install xxx.apk adb install -r xxx.apk 2.卸载APK(如果加 -k 参数,为卸载软件但是保留配置和缓存文件) adb uninstall xxx.apk adb uninstall -k xxx.apk 3.查看当前所有连接的模拟器设备 adb devices 4.对某一模拟器操作 adb -s 模拟器编号 命令 5.导入文件到模拟器 (该命令也可以实现安装AP

如何获得Android设备名称(ADB命令详细介绍)

豌豆荚.360手机管家等软件可以获取Android设备名称,显示在界面上,如下图: 我们自己如何来获取设备名称 呢?答案如下: 在命令行中输入"adb shell"进入shell之后,再输入"cat /system/build.prop"其实,设备信息,主要是存放在"/system/build.prop"文件,通过"cat"命令就可以查看了. 下面附上ADB命令的详细介绍 adb 介绍 adb的全称为Android Debug

Android开发中adb命令的常用方法

Android的SDK中提供了很多有用的工具,在开发过程中如果能熟练使用这些工具,会让我们的开发事半功倍.adb是SDK提供的一个常用的命令行工具,全称为Android Debug Bridge,用于在调试时连接本机和手机设备. adb有很多命令,本文只列出一些常用的命令,要查看所有的adb命令和用法, 可以在命令行中输入adb进行查看. 这些命令都是根据本人在开发过程中的使用进行总结的,以后如果发现其他常用的和有用的命令,会加入本文中.下面是一些常用的命令和用法. 一    adb常用命令 a

Android测试 常用adb命令总结

针对移动端 Android 的测试, adb 命令是很重要的一个点,必须将常用的 adb 命令熟记于心, 将会为 Android 测试带来很大的方便,其中很多命令将会用于自动化测试的脚本当中. Android Debug Bridge adb 其实就是 Android Debug Bridge, Android 调试桥的缩写,adb 是一个 C/S 架构的命令行工具,主要由 3 部分组成: 运行在 PC 端的 Client : 可以通过它对 Android 应用进行安装.卸载及调试 Eclips

Android Studio使用adb命令连接平板

有需要使用adb命令连接调试平板的同学可以参考下(下面是android官方文档,有点老). http://donandroid.com/how-to-install-adb-interface-drivers-windows-7-xp-vista-623 1.android studio 里安装google usb driver,安装完重启Android studio即可. 2.进入电脑设备管理器查看是否安装成功:截图显示是已经安装ok的.  3.找到sdk安装目录,在Android studi