Bonjour,
J'essaye de faire communiquer l'application android(client) avec un PC (serveur). J'arrive bien à recevoir les données du PC sur l'application mais j'arrive pas à envoyer des données du smartphone vers le PC. J'ai fait plusieurs tests :
- en mettant directement dans le doInBackGround : out.println("Coucou"); mais rien ne s'affiche
- j'ai également créer une fonction send_message et quand je l'appelle en cliquant sur un bouton, mon application se ferme.
De plus, j'aimerai que l'application puisse recevoir des données même si elle est fermée mais je ne sais pas comment procédé.


Voici le code de l'application android :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
 
public class MainActivity extends Activity implements TextWatcher, OnClickListener  {
 
	Button lancer = null;
	EditText tduree = null;
	TextView min = null;
	TextView duree = null;
	RadioGroup groupe = null;
	Button historique=null;
	Client client;
 
	public static final int ID_NOTIFICATION = 1900;
 
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
 
		client= new Client();
		client.execute();
 
	   lancer=(Button)findViewById(R.id.lancer);
	   tduree = (EditText) findViewById(R.id.tduree);
	   min = (TextView) findViewById(R.id.min);
	   groupe = (RadioGroup)findViewById(R.id.radioGroup1);
	   duree = (TextView) findViewById(R.id.duree);
	   RadioButton auto = (RadioButton)findViewById(R.id.Auto);    	
	   RadioButton manuel = (RadioButton)findViewById(R.id.Manuel);    	
	   historique=(Button)findViewById(R.id.Historique);          
 
	    // on attribue un listener 
	    tduree.addTextChangedListener(this);
	    auto.setOnClickListener(this);
	    manuel.setOnClickListener(this);
	    lancer.setOnClickListener(envoyerListener);       
	}
 
 
	public void onClick(View v){
	  switch (v.getId()){
	  	case R.id.Auto:
	  		if(min.getVisibility() == View.VISIBLE)
	  			min.setVisibility(View.INVISIBLE);
	  		if(duree.getVisibility() == View.VISIBLE)
	  			duree.setVisibility(View.INVISIBLE);
	  		if(tduree.getVisibility() == View.VISIBLE)
				tduree.setVisibility(View.INVISIBLE); 
	  		if(lancer.getVisibility()==View.VISIBLE)
	  			lancer.setVisibility(View.INVISIBLE);
				break;
		case R.id.Manuel:
			if(min.getVisibility() == View.INVISIBLE)
	  			min.setVisibility(View.VISIBLE);
			if(duree.getVisibility() == View.INVISIBLE)	
				duree.setVisibility(View.VISIBLE);
	    	if(tduree.getVisibility() == View.INVISIBLE)
				tduree.setVisibility(View.VISIBLE); 
	    	if(lancer.getVisibility()==View.INVISIBLE)
	  			lancer.setVisibility(View.VISIBLE);
				break;
	    }
	 }
 
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) { 
    }
 
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count,
      int after) {
    }
 
    @Override
    public void afterTextChanged(Editable s) {
    }
 
 
 
    @SuppressWarnings("deprecation")
	private void createNotify(){
    	//On creer un "gestionnaire de notification"
    	NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        
 
    	//On cree la notification
    	//Avec son icone et son texte defilant (optionel si l'on veut pas de texte defilant on met cet argument a null)
    	Notification notification = new Notification(R.drawable.bebe, "Toc toc, c'est une notification !", System.currentTimeMillis());  
 
    	//Le PendingIntent c'est ce qui va nous permettre d'atteindre notre deuxieme Activity
    	//MainActivity sera donc le nom de notre seconde Activity
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);
        //On definit le titre de la notif
        String titreNotification = "Alerte !";
        //On definit le texte qui caracterise la notif
        String texteNotification = "Le bebe pleurt ...";         
 
        //On configure notre notification avec tous les parametres que l'on vient de creer
        notification.setLatestEventInfo(this, titreNotification, texteNotification, pendingIntent);
        //On ajoute un style de vibration a notre notification
        //L'utilisateur est donc egalement averti par les vibrations de son telephone
        //Ici les chiffres correspondent a 0sec de pause, 0.2sec de vibration, 0.1sec de pause, 0.2sec de vibration, 0.1sec de pause, 0.2sec de vibration
        //Vous pouvez bien entendu modifier ces valeurs a votre convenance
        notification.vibrate = new long[] {0,200,100,200,100,200};
 
        //Enfin on ajoute notre notification et son ID a notre gestionnaire de notification
        notificationManager.notify(ID_NOTIFICATION, notification);
    }
 
 
    //teste avec une classe fille
    class Client extends AsyncTask<Void,Void,String>{
 
    	int numPort = 9550;
		 InetAddress ipaddress;
		 Socket client;
		 PrintWriter out;
		 OutputStream nos; 
		 BufferedReader in;
		 char[] message;
		 String test ;
 
    	public String doInBackground(Void...params){ 		 
       		 try {
       			client = new Socket("10.0.2.2", numPort);
        		in = new BufferedReader(new InputStreamReader(client.getInputStream()));
        		out = new PrintWriter(client.getOutputStream(), true);
 
       		        test = in.readLine(); //fonctionne bien
        		out.println("Coucou");
        		out.flush();*/
 
    		    }catch (IOException e) {
    		    	// TODO Auto-generated catch block
    		    	e.printStackTrace();
    		    }
    		 return test;
    	}
 
    	// methode pour envoyer des donnees
    	void send_message(String message){
		    		out.println(message);//on envoie le message au serveur
		    		out.flush();	
 
    	}
 
    	public void onPostExecute(String result){ // result correspond au parametre envoyer par doInBackGround
             if (result != null) {
 
            	 if(groupe.getCheckedRadioButtonId()==R.id.Manuel){
		    	//createNotify();  //fonctionne mais j'arrive pas à la supprimer une fois lue
            		 TextView tv = (TextView) MainActivity.this.findViewById(R.id.textView1);
		           tv.setText(result);
 
		    		}else{
		  		      String time_arbitraire = "05"; 
				      send_message(time_arbitraire);
 
		    		}
             }
    	}
    }
 
 
 
	//Uniquement pour le bouton lancer
	 public OnClickListener envoyerListener = new OnClickListener() {
	     @Override
		 public void onClick(View v)  {
	    	 //recupere la duree de bercement en char[]
	    	 String time_s = tduree.getText().toString();
	    	 char[] time = time_s.toCharArray();
	    	 client.send_message(time_s);
 
	     }
	  };
 
}
Voici le code du serveur PC :

Code : Sélectionner tout - Visualiser dans une fenêtre à part
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
 
public class serveur {
 
	public static void main(String[] args){
			int b = 0;
			ServerSocket socketserver;
			Socket socketduserveur ;
			BufferedReader in = null ;
			PrintWriter out;
			String rep;
		 try {
 
		      socketserver = new ServerSocket(9550);	      
		      InetAddress address = InetAddress.getLocalHost();
		      String hostIP = address.getHostAddress() ;
			  String hostName = address.getHostName();
			  System.out.println( "Le nom de serveur est : " + hostName + "\nIP: " + hostIP);
			  System.out.println("Le serveur est a l'ecoute du port "+socketserver.getLocalPort());
		      socketduserveur = socketserver.accept();
			  System.out.println("client connecte");
			  out = new PrintWriter(socketduserveur.getOutputStream());
			  out.write("TESTTTT");
			  out.flush();
			  in = new BufferedReader(new InputStreamReader(socketduserveur.getInputStream()));
 
	         }
		 catch (Exception e) {
		      e.printStackTrace();
		      System.out.println("erreur 1");
		    } 
	}
 
}


Voilà les erreurs obtenues lorsque j'appuye sur le bouton "lancer" permettant d'envoyer une donnée au serveur :

05-19 04:50:23.643: W/dalvikvm(912): threadid=1: thread exiting with uncaught exception (group=0xb4a77ba8)
05-19 04:50:23.673: E/AndroidRuntime(912): FATAL EXCEPTION: main
05-19 04:50:23.673: E/AndroidRuntime(912): Process: com.berceauconnecte, PID: 912
05-19 04:50:23.673: E/AndroidRuntime(912): java.lang.NullPointerException
05-19 04:50:23.673: E/AndroidRuntime(912): at com.berceauconnecte.MainActivity$Client.send_message(MainActivity.java:231)
05-19 04:50:23.673: E/AndroidRuntime(912): at com.berceauconnecte.MainActivity$1.onClick(MainActivity.java:271)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.view.View.performClick(View.java:4438)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.view.View$PerformClick.run(View.java:18422)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.os.Handler.handleCallback(Handler.java:733)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.os.Handler.dispatchMessage(Handler.java:95)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.os.Looper.loop(Looper.java:136)
05-19 04:50:23.673: E/AndroidRuntime(912): at android.app.ActivityThread.main(ActivityThread.java:5017)
05-19 04:50:23.673: E/AndroidRuntime(912): at java.lang.reflect.Method.invokeNative(Native Method)
05-19 04:50:23.673: E/AndroidRuntime(912): at java.lang.reflect.Method.invoke(Method.java:515)
05-19 04:50:23.673: E/AndroidRuntime(912): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
05-19 04:50:23.673: E/AndroidRuntime(912): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
05-19 04:50:23.673: E/AndroidRuntime(912): at dalvik.system.NativeStart.main(Native Method)
05-19 04:50:26.233: I/Process(912): Sending signal. PID: 912 SIG: 9
Je vous remercie d'avance