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

本文介绍了一种利用Socket技术实现在PC端通过命令远程控制手机的操作方法,包括界面切换和屏幕滑动等功能。具体实现分为手机端和服务端两部分,手机端启动Service监听PC端连接并响应命令,服务端处理PC端发来的命令并执行相应的手机操作。
AI助手已提取文章相关产品:

本文在此基础上做了一些修改:http://blog.youkuaiyun.com/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端的代码比较简单。


您可能感兴趣的与本文相关内容

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值