Understanding android UDP server app code -
i'm novice both android , java. i'm trying develop simple udp server first android app (the second 1 if consider hello world!). i've collected code web , result:
package com.example.androidsocketserver; import java.net.datagrampacket; import java.net.datagramsocket; import android.app.activity; import android.widget.textview; public class mainactivity extends activity { public void updatetextview(string tothis) { textview textview = (textview) findviewbyid(android.r.id.text2); textview.settext(tothis); } private mydatagramreceiver mydatagramreceiver = null; protected void onresume() { mydatagramreceiver = new mydatagramreceiver(); mydatagramreceiver.start(); } protected void onpause() { mydatagramreceiver.kill(); } private class mydatagramreceiver extends thread { private boolean bkeeprunning = true; public void run() { string message; byte[] lmessage = new byte[200]; datagrampacket packet = new datagrampacket(lmessage, lmessage.length); try { datagramsocket socket = new datagramsocket(2500); while(bkeeprunning) { socket.receive(packet); message = new string(lmessage, 0, packet.getlength()); if (message != null) { updatetextview(message); message = null; } } if (socket != null) { socket.close(); } } catch (throwable e) { e.printstacktrace(); } } public void kill() { bkeeprunning = false; } } }
unfortunately application stopped launch it, don't understand why.
there kind me understand missed. tryed emulator , real device obtaining same result.
thank in advance.
whithout error difficult know fault try changing receiver class async task
public class receiverbroadcastasynctask extends asynctask<void, integer ,string > { boolean running = true; context context; //public int counter = 1; public receiverbroadcastasynctask(context context) { this.context = context.getapplicationcontext(); } @override protected string doinbackground(void... params) { /////here code } protected void onpostexecute(string result) { //do whatever...nothing required pass result on finish } protected void onprogressupdate(integer... progress) { ///you can pass data on here on task progress inform status } }
from activity can call async task
new receiverbroadcastasynctask(this).execute(); ///this refers context
Comments
Post a Comment