Red en Android LSUB, GYSC, URJC
Red en Android Igual que en Java Algunas peculiaridades con el interfaz (WIFI lock) Se puede emular
Cliente public void hola(view button){ int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola", time); msg.show(); Thread c = new Thread(){ @Override public void run() { Socket s; OutputStream o; o = null; try{ s = new Socket("10.0.2.2", 2000); OutputStream o = s.getoutputstream(); byte buf[] = "hola hola".getbytes("utf-8"); o.write(buf, 0, buf.length); }
Cliente!! } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(unknownhostexception e){ System.out.println("cannot connect to host " + e); } catch(ioexception e){ System.out.println("IO exception" + e); } finally { if o!= null o.close() } } } }; c.start();
Permisos Como para muchos recursos hay que pedir permiso al usuario Se declaran los permisos que se necesitan en el manifest
Permisos (cliente o servidor) <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.client" android:versioncode="1" android:versionname="1.0" >! <uses-sdk android:minsdkversion="8" android:targetsdkversion="17" /> <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.client.mainactivity" android:label="@string/app_name" >...
! Servidor try{ ServerSocket s = new ServerSocket(1234); OutputStream o; o = null; while(true){ Socket sin = s.accept(); if(sin == null) break; o = sin.getoutputstream(); byte buf[] = "hola hola".getbytes("utf-8"); o.write(buf, 0, buf.length); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(unknownhostexception e){ System.out.println("cannot connect to host " + e); } catch(ioexception e){ System.out.println("IO exception" + e); } finally { if o!= null o.close() }
Información de Interfaces La clase WifiInfo (ojo, en el emulador no funciona). Necesita el permiso:! <uses-permission android:name="android.permission.access_wifi_state" />
Información de Interfaces WifiManager wifimanager = (WifiManager) getsystemservice(wifi_service); WifiInfo wifiinfo = wifimanager.getconnectioninfo(); int ipaddress = wifiinfo.getipaddress(); String ip = String.format("%d.%d.%d.%d", ipaddress & 0xff, ipaddress>>8 & 0xff, ipaddress>>16 & 0xff, ipaddress>>24 & 0xff); int time = Toast.LENGTH_SHORT; Toast msg = Toast.makeText(this, "hola soy: " + ip, time); msg.show();
WIFI lock En cuanto deja de haber actividad se apaga la WIFI (aunque haya conexiones abiertas) Si no quiero que se me de problemas puedo hacer que se quede encendida Si el usuario la apaga, se apaga
WIFI lock Mejor por cuenta de referencias Así, creo uno sólo para mi App y me despreocupo
WIFI lock WifiManager wm = (WifiManager) context.getsystemservice(context.wifi_service); wifilock = wm.createwifilock(wifimanager.wifi_mode_full, MyWifiLock ); // Poner cuenta de referencias wifilock.setreferencecounted(true); // Coger el cierre wifilock.acquire(); // Usar la red // Coger el cierre wifilock.release(); Log.i( Mi_app, "WiFi Lock released! );
WIFI lock Tengo que pedir el permiso:! <uses-permission android:name="android.permission.wake_lock" />
3G Detrás de NAT (en muchas WIFIs también) Lo mejor es usar un servidor para comunicarse
Emular la Red Todo lo que hay que saber: http://developer.android.com/tools/devices/ emulator.html#emulatornetworking
Depuración Usar telnet o nc para depurar (se puede redireccionar la entrada y usar una fifo creada con mkfifo) Así nos fiamos de uno de los lados mientras depuramos el otro
Emular la Red Puerto de control
Emular la red Simulador Gateway 10.0.2.15 10.0.2.1 1234 325 Host Simulador 10.0.2.15 Gateway 10.0.2.1 127.0.0.1 == 10.0.2.2 Las direcciones que ven los emuladores son siempre las mismas
Emular la red Redireccionar el puerto del NAT (de entrada al dispositivo) $ telnet localhost 5554 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. Android Console: type 'help' for a list of commands OK redir add tcp:325:1234 OK!
Emular la red (servidor)! try{ ServerSocket s = new ServerSocket(1234); while(true){ Socket sin = s.accept(); if(sin == null) break; OutputStream o = sin.getoutputstream(); byte buf[] = "hola hola".getbytes("utf-8"); o.write(buf, 0, buf.length); o.close(); } s.close(); } catch (ConnectException e){ System.out.println("connection refused" + e); } catch(unknownhostexception e){ System.out.println("cannot connect to host " + e); } catch(ioexception e){ System.out.println("IO exception" + e); }
Depuración (servidor:android, cliente: telnet) $ telnet localhost 1234 Trying ::1... telnet: connect to address ::1: Connection refused Trying 127.0.0.1... Connected to localhost. Escape character is '^]'. hola hola Connection closed by foreign host. $
Depuración: (cliente:android, servidor: nc) Es cómodo poner un netcat de servidor para probar Ej: cliente en el dispositivo, conecta a 10.0.2.2:2000 en la shell ejecuto: $ nc -l 2000
Depuración! s = new Socket("10.0.2.2", 2000); OutputStream o = s.getoutputstream(); byte buf[] = "hola hola\n".getbytes("utf-8"); o.write(buf, 0, buf.length); o.close();
Depuración $ nc -l 2000 hola hola $
Automatización: adb Para hacerle cosas al emulador automáticamente desde la shell Por ejemplo levantar el interfaz de red y cambiar a 3G, cambiar el forward de puertos, etc. http://developer.android.com/tools/help/ adb.html#move
WIFI direct Conectar dos teléfonos directamente Sin access point Sin bluetooth (protocolo roto en muchos teléfonos y no llega muy lejos)