I have an application android who send data to the server (PC) but I don't receive any data from the PC to the application. And, how can I do a listener for incoming UDP messages ?
because I need an app to be running all the time even if the app is closed. How would I ensure that my 'listener' service is always running? I would like to receive a notification when a message arrive from the server to the smartphone.
Here is my code :
public class MainActivity extends Activity implements TextWatcher, OnClickListener {
Client client;
EnvoyerMess envoyermessage;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
client = new Client();
client.execute();
lancer.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View v) {
envoyermessage=new EnvoyerMess();
envoyermessage.execute();
}
});
}
class Client extends AsyncTask<Void,Void,String>{
DatagramSocket client;
String test ;
public String doInBackground(Void...params){
String result=null;
int port=4000;
DatagramSocket clientSocket = null;
byte[] receiveData = new byte[256];
DatagramPacket packet = new DatagramPacket(receiveData, receiveData.length);
try{
InetAddress adresse = InetAddress.getByName("10.0.2.2");
clientSocket = new DatagramSocket(port);
clientSocket.receive(packet);
result = new String(packet.getData());
Log.d("","Received :) ");
}catch (Exception e) {
e.printStackTrace();
} finally {
if (clientSocket != null) {
clientSocket.close();
}
}
return result;
}
public void onPostExecute(String result){
if (result != null) {
//createNotify();
TextView tv = (TextView) MainActivity.this.findViewById(R.id.textView1);
tv.setText(result);
}
}
thanks in advance..