主类androidService.java
/**
* 设置:android手机
*
*/
public class androidService extends Service {
public static final String TAG = "TAG";
public static Boolean mainThreadFlag = true;
public static Boolean ioThreadFlag = true;
ServerSocket serverSocket = null;
final int SERVER_PORT = 10086;
File testFile;
private sysBroadcastReceiver sysBR;
@Override
public void onCreate() {
super.onCreate();
Log.v(TAG, Thread.currentThread().getName() + "---->" + " onCreate");
//创建内部类sysBroadcastReceiver 并注册registerReceiver
sysRegisterReceiver();
new Thread() {
public void run() {
doListen();
};
}.start();
}
private void doListen() {
Log.d(TAG, Thread.currentThread().getName() + "---->"
+ " doListen() START");
serverSocket = null;
try {
Log.d(TAG, Thread.currentThread().getName() + "---->"
+ " doListen() new serverSocket");
serverSocket = new ServerSocket(SERVER_PORT);
boolean mainThreadFlag = true;
while (mainThreadFlag) {
Log.d(TAG, Thread.currentThread().getName() + "---->"
+ " doListen() listen");
Socket client = serverSocket.accept();
new Thread(new ThreadReadWriterIOSocket(this, client)).start();
}
} catch (IOException e1) {
Log.v(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "new serverSocket error");
e1.printStackTrace();
}
}
/* 创建内部类sysBroadcastReceiver 并注册registerReceiver */
private void sysRegisterReceiver() {
Log.v(TAG, Thread.currentThread().getName() + "---->"
+ "sysRegisterReceiver");
sysBR = new sysBroadcastReceiver();
/* 注册BroadcastReceiver */
IntentFilter filter1 = new IntentFilter();
/* 新的应用程序被安装到了设备上的广播 */
filter1.addAction("android.intent.action.PACKAGE_ADDED");
filter1.addDataScheme("package");
filter1.addAction("android.intent.action.PACKAGE_REMOVED");
filter1.addDataScheme("package");
registerReceiver(sysBR, filter1);
}
/* 内部类:BroadcastReceiver 用于接收系统事件 */
private class sysBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equalsIgnoreCase("android.intent.action.PACKAGE_ADDED")) {
// ReadInstalledAPP();
} else if (action
.equalsIgnoreCase("android.intent.action.PACKAGE_REMOVED")) {
// ReadInstalledAPP();
}
Log.v(TAG, Thread.currentThread().getName() + "---->"
+ "sysBroadcastReceiver onReceive");
}
}
@Override
public void onDestroy() {
super.onDestroy();
// 关闭线程
mainThreadFlag = false;
ioThreadFlag = false;
// 关闭服务器
try {
Log.v(TAG, Thread.currentThread().getName() + "---->"
+ "serverSocket.close()");
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.v(TAG, Thread.currentThread().getName() + "---->"
+ "**************** onDestroy****************");
}
@Override
public void onStart(Intent intent, int startId) {
Log.d(TAG, Thread.currentThread().getName() + "---->" + " onStart()");
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent arg0) {
Log.d(TAG, " onBind");
return null;
}
}
用于新socket连接的读写线程类ThreadReadWriterIOSocket.java
package com.otheri.service;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.content.Context;
import android.util.Log;
import com.otheri.util.FileHelper;
import com.otheri.util.MyUtil;
/**
* 功能:用于socket的交互
*
* @author wufenglong
*
*/
public class ThreadReadWriterIOSocket implements Runnable {
private Socket client;
private Context context;
ThreadReadWriterIOSocket(Context context, Socket client) {
this.client = client;
this.context = context;
}
@Override
public void run() {
Log.d(androidService.TAG, Thread.currentThread().getName() + "---->"
+ "a client has connected to server!");
BufferedOutputStream out;
BufferedInputStream in;
try {
/* PC端发来的数据msg */
String currCMD = "";
out = new BufferedOutputStream(client.getOutputStream());
in = new BufferedInputStream(client.getInputStream());
// testSocket();// 测试socket方法
androidService.ioThreadFlag = true;
while (androidService.ioThreadFlag) {
try {
if (!client.isConnected()) {
break;
}
/* 接收PC发来的数据 */
Log.v(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "will read......");
/* 读操作命令 */
currCMD = readCMDFromSocket(in);
Log.v(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "**currCMD ==== " + currCMD);
/* 根据命令分别处理数据 */
if (currCMD.equals("4")) {
/* 准备接收文件数据 */
try {
out.write("service receive OK".getBytes());
out.flush();
} catch (IOException e) {
e.printStackTrace();
}
/* 接收文件数据,4字节文件长度,4字节文件格式,其后是文件数据 */
byte[] filelength = new byte[4];
byte[] fileformat = new byte[4];
byte[] filebytes = null;
/* 从socket流中读取完整文件数据 */
filebytes = receiveFileFromSocket(in, out, filelength,
fileformat);
// Log.v(Service139.TAG, "receive data =" + new
// String(filebytes));
try { /* 生成文件 */
File file = FileHelper.newFile("R0013340.JPG");
FileHelper.writeFile(file, filebytes, 0,
filebytes.length);
} catch (IOException e) {
e.printStackTrace();
}
} else if (currCMD.equals("exit")) {
}
} catch (Exception e) {
// try {
// out.write("error".getBytes("utf-8"));
// out.flush();
// } catch (IOException e1) {
// e1.printStackTrace();
// }
Log.e(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "read write error111111");
}
}
out.close();
in.close();
} catch (Exception e) {
Log.e(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "read write error222222");
e.printStackTrace();
} finally {
try {
if (client != null) {
Log.v(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "client.close()");
client.close();
}
} catch (IOException e) {
Log.e(androidService.TAG, Thread.currentThread().getName()
+ "---->" + "read write error333333");
e.printStackTrace();
}
}
}
//功能:从socket流中读取完整文件数据
}
}
testPcClient.java
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class testPcClient {
/**
* @param args
* @throws InterruptedException
*/
public static void main(String[] args) throws InterruptedException {
try {
Runtime.getRuntime().exec(
"adb shell am broadcast -a NotifyServiceStop");
Thread.sleep(3000);
Runtime.getRuntime().exec("adb forward tcp:12580 tcp:10086");
Thread.sleep(3000);
Runtime.getRuntime().exec(
"adb shell am broadcast -a NotifyServiceStart");
Thread.sleep(3000);
} catch (IOException e3) {
e3.printStackTrace();
}
Socket socket = null;
try {
InetAddress serverAddr = null;
serverAddr = InetAddress.getByName("127.0.0.1");
System.out.println("TCP 1111" + "C: Connecting...");
socket = new Socket(serverAddr, 12580);
String str = "hi,wufenglong";
System.out.println("TCP 221122" + "C:RECEIVE");
BufferedOutputStream out = new BufferedOutputStream(socket
.getOutputStream());
BufferedInputStream in = new BufferedInputStream(socket
.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(
System.in));
boolean flag = true;
while (flag) {
System.out.print("请输入1~6的数字,退出输入exit:");
String strWord = br.readLine();// 从控制台输入1~6
if (strWord.equals("4")) {
/* 发送命令 */
out.write("4".getBytes());
out.flush();
System.out.println("send file finish sending the CMD:");
/* 服务器反馈:准备接收 */
String strFormsocket = readFromSocket(in);
System.out
.println("service ready receice data:UPDATE_CONTACTS:"
+ strFormsocket);
byte[] filebytes = FileHelper.readFile("R0013340.JPG");
System.out.println("file size=" + filebytes.length);
/* 将整数转成4字节byte数组 */
byte[] filelength = new byte[4];
filelength = tools.intToByte(filebytes.length);
/* 将.apk字符串转成4字节byte数组 */
byte[] fileformat = null;
fileformat = ".apk".getBytes();
System.out
.println("fileformat length=" + fileformat.length);
/* 字节流中前4字节为文件长度,4字节文件格式,以后是文件流 */
/* 注意如果write里的byte[]超过socket的缓存,系统自动分包写过去,所以对方要循环写完 */
out.write(filelength);
out.flush();
String strok1 = readFromSocket(in);
System.out.println("service receive filelength :" + strok1);
// out.write(fileformat);
// out.flush();
// String strok2 = readFromSocket(in);
// System.out.println("service receive fileformat :" +
// strok2);
System.out.println("write data to android");
out.write(filebytes);
out.flush();
System.out.println("*********");
/* 服务器反馈:接收成功 */
String strread = readFromSocket(in);
System.out.println(" send data success:" + strread);
System.out
.println("=============================================");
}
}
/* 从InputStream流中读数据 */
public static String readFromSocket(InputStream in) {
int MAX_BUFFER_BYTES = 4000;
String msg = "";
byte[] tempbuffer = new byte[MAX_BUFFER_BYTES];
try {
int numReadedBytes = in.read(tempbuffer, 0, tempbuffer.length);
msg = new String(tempbuffer, 0, numReadedBytes, "utf-8");
tempbuffer = null;
} catch (Exception e) {
e.printStackTrace();
}
// Log.v(Service139.TAG, "msg=" + msg);
return msg;
}
}
android端和pc端使用usb进行socket通信,其中android是服务器端,pc是客户端。如何实现安卓端输入的数据通过按钮发送到pc端?
部分源码如下: