Android开发之无线遥控器

时间:2021-05-29 09:28:44

最近弄了一个UDP/TCP的小东西,主要需要实现的功能如下(服务器端):

1、基于局域网

2、服务器端网络接口为无线与有线

3、服务器端接收到客户端的数据需要模拟按键进行处理

4、开机自启动

5、使用UDP进行连接,TCP进行通讯

基于以上几点,我们开始分析:

1.需要获取当前的网络IP地址,这里枚举了本机所有的网络地址,只返回ipv4

 public String getAddressIP() {
//检查网络是否连接
while (!isNetWorkConnected()) {
//等待网络连接
}
ip = getLocalIpAddress();
return ip;
} public String getLocalIpAddress() {
String address = null;
try {
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress()) {//127.0.0.1
address = inetAddress.getHostAddress().toString();
//ipV6
if(!address.contains("::")){
return address;
}
}
}
}
} catch (SocketException ex) {
Log.e("getIpAddress Exception", ex.toString());
}
return null;
} private boolean isNetWorkConnected() {
// TODO Auto-generated method stub
try{
connectivity = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivity != null){
netWorkinfo = connectivity.getActiveNetworkInfo();
if(netWorkinfo != null && netWorkinfo.isAvailable()){
if(netWorkinfo.getState() == NetworkInfo.State.CONNECTED){
isConnected = true;
return true;
}
}
}
}catch(Exception e){
Log.e("UdpService : ",e.toString());
return false;
}
return false;
}

2.获得IP之后,创建一个多播组

       try {

             while(ip == null){
ip = getAddressIP();
} inetAddress = InetAddress.getByName(BROADCAST_IP);//多点广播地址组
multicastSocket = new MulticastSocket(BROADCAST_PORT);//多点广播套接字
multicastSocket.setTimeToLive(1);
multicastSocket.joinGroup(inetAddress); } catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

这里设置一组特殊网络地址作为多点广播地址,第一个多点广播地址都被看作是一个组,当客户端需要发送接收广播信息时,加入该组就可以了。

IP协议为多点广播提供这批特殊的IP地址,这些IP地址范围是224.0.0.0---239.255.255.255,其中224.0.0.0为系统自用。

下面BROADCAST_IP是自己声明的一个String类型的变量,其范围也是前面所说的IP范围,比如BROADCAST_IP="224.224.224.224"。

     private static int BROADCAST_PORT = 1234;
private static int PORT = 4444;
private static String BROADCAST_IP = "224.0.0.1";

3.服务端开始发送本机IP地址广播,如果网络断开,则结束掉此线程,并设置标识

     public class UDPBoardcastThread extends Thread {
public UDPBoardcastThread() {
this.start();
} @Override
public void run() {
DatagramPacket dataPacket = null;
//将本机的IP地址放到数据包里
byte[] data = ip.getBytes();
dataPacket = new DatagramPacket(data, data.length, inetAddress, BROADCAST_PORT);
//判断是否中断连接了
while (isNetWorkConnected()) {
try {
multicastSocket.send(dataPacket);
Thread.sleep(5000);
Log.i("UDPService:","再次发送ip地址广播");
} catch (Exception e) {
e.printStackTrace();
}
}
isConnected = false;
Message msg = new Message();
msg.what = 0x0001;
mHandler01.sendMessage(msg); }
}

4.新开一个线程,等待客户端连接,使用TCP进行通讯

             new Thread() {
@Override
public void run() {
try {
//建立一个线程池,每次收到一个客户端,新开一个线程
mExecutorService = Executors.newCachedThreadPool();
Socket client = null;
mList.clear();
while (isConnected) { client = server.accept();
//把客户端放入客户端集合中
if (!connectOrNot(client)) {
mList.add(client);
Log.i("UDPService","当前连接数:"+mList.size());
}
mExecutorService.execute(new Service(client));
}
//释放客户端
for(int i = 0 ; i < mList.size() ; i++)
mList.get(i).close(); } catch (IOException e) {
e.printStackTrace();
}
}
}.start();

5.新开一个客户端的线程,处理客户端发送过来的数据等

     //客户端线程,组成线程池
class Service implements Runnable {
private Socket socket;
private BufferedReader in = null;
private String msg = ""; public Service(Socket socket) {
this.socket = socket;
} @Override
public void run() {
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//等待接收客户端发送的数据
while (isConnected) { if ((msg = in.readLine()) != null) { // 创建一个Instrumentation对象,调用inst对象的按键模拟方法
Instrumentation inst = new Instrumentation();
try{
int codeKey = Integer.parseInt(msg);
//codeKey对应键值参照KeyCodeTable.txt文件,在客户端中实现
inst.sendKeyDownUpSync(codeKey); //发送回执
this.sendmsg(socket);
}catch(Exception ex){
ex.printStackTrace();
} }
}
} catch (Exception e) {
e.printStackTrace();
}
} private void sendmsg(Socket socket2) {
// TODO Auto-generated method stub
PrintWriter pout = null; try {
pout = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket2.getOutputStream())), true);
pout.println("I am ok");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

这里使用了Instrumentation()对象来模拟按键的处理,在实际使用中,效率还行,没有很严重的延时,若真有延时,感觉也是网络方面的。

使用了socket.getInputStream()与socket.getOutputStream()方法来进行socket数据的接收与发送

6.最后新开一个Handler对网络断开时进行处理,也可以监听系统网络变化的广播,有时间研究下service的生命周期

     private Handler mHandler01 = new Handler(){

         @Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
switch(msg.what){
//连接失败
case 0x0001:
initData();
break;
}
} };

7.开机自启动,继承BroadcastReceiver,监听系统开机广播就ok了,记得在AndroidManifest.xml文件中声明BOOT_COMPLETED属性

     if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")){
Intent intent2 = new Intent(context, UdpService.class);
context.startService(intent2);
}

8.还有一个问题,如果我们就这样直接编译,输出apk到电视中,会出现权限不足的error,原因是apk不是系统应用,只有uid为system id才可以去模拟按键事件,所以在

AndroidManifest.xml中加上android:sharedUserId="android.uid.system",以及<uses-permission android:name="android.permission.INJECT_EVENTS" />

再编写Android.mk,最后在android源码中使用mm命令编译apk,这样就ok了。

服务器端的流程差不多是这样了,附上完整源码,包含服务器端与客户端Demo:

http://download.csdn.net/detail/u012062785/9684842

thread与runnable的区别:https://www.oschina.net/question/565065_86563