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

时间:2021-12-12 10:12:55

 

Android端的代码:

布局文件:activity_main.xml

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
<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>
View Code

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

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
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));
            
        }
    }
}
View Code

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

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
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;
        }
    }
}
View Code

MainActivity.java

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
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) {

        }
    }
}
View Code

 MyUtils.java

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
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;
    }
}
View Code

IMessage.java

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
public interface IMessage {
    
    void sendMsg(String msg);
    
    void receiveMsg(Handler hander);
}
View Code

AndroidManifest.xml

Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
<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>
View Code

作者:sufish

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

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