1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| public class ServiceUDP extends Service {
DatagramSocket datagramSocket;
DatagramPacket packet;
Boolean continuer = true;
String message2;
Thread UDPThread;
void ListenUDP () {
UDPThread = new Thread(new Runnable() {
@Override
public void run() {
try {
datagramSocket = new DatagramSocket(5053);
} catch (SocketException e1) {
e1.printStackTrace();
}
byte [] buffer = new byte[1024];
packet = new DatagramPacket(buffer,buffer.length);
while (continuer) {
try
{
datagramSocket.receive(packet);
final String message = new String(packet.getData(),0,packet.getLength());
message2=message +System.getProperty("line.separator");
try {
FileOutputStream out = openFileOutput("test12.txt",MODE_APPEND);
out.write(message2.getBytes());
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
});
UDPThread.start();
}
@Override
public void onCreate() {
}
@Override
public int onStartCommand (Intent intent , int flags , int startID) {
ListenUDP();
return START_STICKY;
}
public IBinder onBind(Intent intent)
{
return null;
}
} |
Partager