Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)
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/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。如有问题,可以邮件:dotnetframework@sina.com联系我,非常感谢。
Android笔记之adb命令应用实例1(手机端与PC端socket通讯上)的更多相关文章
- Android笔记之adb命令应用实例1(手机端与PC端socket通讯下)
通过adb和Android通讯需要引用adb相关的组件到项目中,分别为:adb.exe,AdbWinApi.dll,AdbWinUsbApi.dll. 可以在XXX\sdk\platform-tool ...
- Android笔记之adb命令解析1
要在cmd命令中直接使用adb,需要配置环境变量:目录XXX\sdk\platform-tools 查看adb -help 帮助命令打印出以下内容: Android Debug Bridge vers ...
- Android笔记(adb命令--reboot loader)
Android 的机器通过adb进入升级模式的方法 # adb shell # reboot loader 通过上面两个命令就进入升级模式了,通过工具升级就好了 为什么会写这简单的一篇呢?因为今天干了 ...
- Android的常用adb命令
第一部分:1. ubuntu下配置环境anroid变量:在终端执行 sudo gedit /etc/profile 打开文本编辑器,在最后追加#setandroid environment2. 运行E ...
- android学习笔记31——ADB命令
使用Adb shell command直接送key event給Androidadb shell input keyevent 7 # for key '0'adb shell input keyev ...
- android studio 使用adb命令传递文件到android设备
一:文件传输 在android开发中,有时候需要将文件从pc端传递至android,或者将软件运行的日志,从android设备传递到pc进行分析,我们可以使用windows的cmd窗口,或者andro ...
- Android 里的adb命令
ADB的全称为Android Debug Bridge,就是起到调试桥的作用. adb调试手机需要把usb调试打开 Android studio模拟器有的也要把模拟器usb调试打开,工具要灵活运用, ...
- Android开发中adb命令的常用方法
Android的SDK中提供了很多有用的工具,在开发过程中如果能熟练使用这些工具,会让我们的开发事半功倍.adb是SDK提供的一个常用的命令行工具,全称为Android Debug Bridge,用于 ...
- 如何获得Android设备名称(ADB命令详细介绍)
豌豆荚.360手机管家等软件可以获取android设备名称,显示在界面上,如下图: 我们自己如何来获取设备名称 呢?答案如下: 在命令行中输入“adb shell”进入shell之后,再输入“cat ...
随机推荐
- SpringMVC(二)
今天在完成的工作的前提下,最终在睡觉前将SpringMVC和Mybatis整合了~~~ 其实就是按照从网上(参考http://www.toutiao.com/a6332703083554324737/ ...
- Notes(一)
Numerous experimental measurements in spatially complex systems have revealed anomalous diffusion in ...
- 2014 ACM/ICPC 鞍山赛区现场赛 D&I 解题报告
鞍山现场赛结束了呢-- 我们出的是D+E+I三道题-- 吾辈AC掉的是D和I两道,趁着还记得.先在这里写一写我写的两道水题D&I的解题报告吧^_^. D题的意思呢是说星云内有一堆排成一条直线的 ...
- 传微软欲收购Xamarin:未来有望通过VS开发iOS和Android应用?
据CRN报道,其援引匿名人士的消息称,微软将收购一家创建C#移动应用工具的公司或进行注资,并且谈判已经到了最终阶段.这家公司的名字叫做Xamarin,创建于2011年.对于微软来说,收购Xamarin ...
- C++容器类对象函数參数问题
总之中的一个句话:容器类对象作为函数參数,与整数类型作为函数參数的传递特性同样. 验证程序 #include "stdafx.h" #include <iostream> ...
- XMLHTTP使用具体解释
XMLHTTP对象是Microsoft的MSXML开发包中带的一个用HTTP,XML协议訪问web资源的对象. 从MSXML3.0開始出现. 它在AJAX技术中主要用来从其它网络资源获取信息,然后由j ...
- Linux开发环境搭建与使用——ubuntu更新设置
ubuntu操作系统公布时,为了减小操作系统的体积,只配备了主要的系统软件.应用软件.我们开发中须要用到的大部分软件都须要在使用中从网上自行更新. 假设ubuntu没有网络,能够说寸步难行. 以下教大 ...
- Config the Android 5.0 Build Environment
In this document Choosing a Branch Setting up a Linux build environment Installing the JDK ...
- MySQL使用hugepage
http://blog.csdn.net/dba_waterbin/article/details/9669929http://www.cnblogs.com/LMySQL/p/4689868.htm ...
- C#_LINQ(LINQ to Entities)
LINQ to Entities 是 LINQ 中最吸引人的部分.它让你可以使用标准的 C# 对象与数据库的结构和数据打交道.使用 LINQ to Entities 时,LINQ 查询在后台转换为 S ...