实现Android手机(服务端)与PC(客户端)实现通信

时间:2022-05-20 00:00:10

本文在此基础上做了一些修改:http://blog.csdn.net/wufenglong/article/details/5778862

  我主要是要通过在PC端发送命令控制手机作出相应的反应,比如界面的切换,屏幕的滑动。手机和PC通过Socket进行通信,手机作为服务端监听PC端的连接请求,连接成功后接受命令。所以在这里需要两个部分来实现,一个手机端和一个服务端。

  1.手机端:在手机需要启动一个Service来监听PC端的Socket的连接请求,这个是不能放在Activity里面,否则程序会“死掉”的。在这里我通过一个Activity来启动Service的:

public class ServerActivity extends Activity {
/** Called when the activity is first created. */
Button start, stop;
private static final String str = "edu.hdu.server.SERVICE";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

start = (Button) findViewById(R.id.start);
stop = (Button) findViewById(R.id.stop);

//创建启动service的Intent
final Intent intent = new Intent();
//为Intent设置Action属性
intent.setAction(str);

start.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
startService(intent);//启动对应的Service
}
});

stop.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0)
{
stopService(intent);//关闭对应的Service
}
});
}
}
下面是Service的实现:它的主要工作是侦听客户端的请求,并启动一个线程IOSocket来处理PC端发来的命令。里面有个Handler是用来处理IOSocket线程发来的消息的,实现屏幕的切换:

public class AndroidService extends Service{

public static Boolean mainThreadFlag = true;
public static Boolean ioThreadFlag = true;
ServerSocket serverSocket = null;
final int SERVER_PORT = 10086;
private int currentId = 0;
//这个Handler用来处理IOSocket线程发来的消息
Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
if (msg.what == 0x1)
{
if (currentId > 2)
{
currentId = 0;
}
if (currentId == 0)
{
currentId++;
Intent intent = new Intent(AndroidService.this,FirstActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if (currentId == 1)
{
currentId++;
Intent intent = new Intent(AndroidService.this,SecondActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if (currentId == 2)
{
currentId++;
Intent intent = new Intent(AndroidService.this,ServerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
};

public IBinder onBind(Intent arg0)
{
return null;
}

public void onCreate()
{
System.out.println("Service is created");
super.onCreate();
new Thread()
{
public void run()
{
doListen();
};
}.start();
}

private void doListen()
{
serverSocket = null;
try
{
serverSocket = new ServerSocket(SERVER_PORT);

boolean mainThreadFlag = true;
while (mainThreadFlag)
{ //侦听有没有来自客户端的连接,没有连接一直阻塞在这里
Socket client = serverSocket.accept();

new Thread(new IOSocket(handler, client)).start();
}
}catch(IOException e)
{
e.printStackTrace();
}
}

public void onDestory()
{
super.onDestroy();

//关闭线程
mainThreadFlag = false;
ioThreadFlag = false;
//关闭服务器
try
{
serverSocket.close();
}catch (IOException e)
{
e.printStackTrace();
}
}

public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
return START_STICKY;
}
}
类IOSocket用来处理PC端的命令,并根据命令向主线程发送消息:

public class IOSocket implements Runnable{
private Handler handler;
private Socket client;


public IOSocket(Handler handler, Socket client)
{
this.handler = handler;
this.client = client;
}

public void run()
{
//BufferedOutputStream out;
BufferedInputStream in;
try
{

//out = new BufferedOutputStream(client.getOutputStream());
in = new BufferedInputStream(client.getInputStream());
//PC端发来的命令
String order = "";
//测试socket
AndroidService.ioThreadFlag = true;
while (AndroidService.ioThreadFlag)
{
try
{
if (!client.isConnected())
{
break;
}


//读取PC发送过来的命令
order = readCMDFromSocket(in);

/* 根据命令分别处理数据 */
if (order.equals("switch"))
{
Message msg = new Message();
msg.what = 0x1;
handler.sendMessage(msg);
//out.write("OK".getBytes());
//out.flush();
}
else if (order.equals("otherOrder"))
{
//out.write("OK".getBytes());
//out.flush();
}
else if (order.equals("exit"))
{

}
}catch (Exception e)
{
e.printStackTrace();
}
}
//out.close();
in.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
try
{
if (client != null)
{
client.close();
}
}catch(IOException e)
{
e.printStackTrace();
}
}
}
/* 读取命令 */
public static String readCMDFromSocket(InputStream in)
{
int MAX_BUFFER_BYTES = 2048;
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();
}
return msg;
}

}
PC端的代码比较简单。