Actually I want to send data from a hardware piece to an android device.
The hardware device is connected to local wireless router which is connected to modem.
Android device will also connected to same router through WI-FI.
Can you please suggest some links or tutorial from where i can get idea how to establish communication between hardware device an the android device to send and receive data through WI-FI .Please Help any sample code or links
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class SimpleClientActivity extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button) findViewById(R.id.button1); //reference to the send button
text = (TextView) findViewById(R.id.textView1); //reference to the text view
//Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
File file = new File("/mnt/sdcard/input.jpg"); //create file instance, file to transfer or any data
try {
client = new Socket("10.0.2.2", 4444);// ip address and port number of ur hardware device
byte[] mybytearray = new byte[(int) file.length()]; //create a byte array to file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(mybytearray, 0, mybytearray.length); //read the file
outputStream = client.getOutputStream();
outputStream.write(mybytearray, 0, mybytearray.length); //write file to the output stream byte by byte
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
// to send message u can also use below code
public static String ipAddress;// ur ip
public static int portNumber;// portnumber
private Socket client;
private OutputStreamWriter printwriter;
private String message;
new Thread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
try {
client = new Socket(ipAddress, portNumber);
printwriter = new OutputStreamWriter(client
.getOutputStream(), "ISO-8859-1");
printwriter.write("any message");
printwriter.flush();
printwriter.close();
client.close();
}
catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
Related
I'm trying to send data from arduino to android app through esp8266. For the moment, arduino and android app are connected via the esp8266 using the TCP/IP socket API. However, when trying to send data continuosly from the arduino it's recieved only once by the android app. In fact, the message is well received by the app only when I proceed the AT+CLOSE command to close the socket and end communication. This method enables me to get the data only one time. So, I have tried to try configure the communication another time after closing it ( please check my code)
void loop()
{
if(Serial1.available())
{
Serial.println("heeeere");
int connectionId = Serial1.read()-48;
while(analogRead(4)>0)
{
convertedvalue = String((analogRead(4)*5)/1024); //convert read analog value before sending it to the android app
convertedvaluelength = String(convertedvalue.length()); //get the length of the converted value
content = "Converted value is "; //make the response to be send to the android app
content += convertedvalue; //make the response to be send to the android app
sendCIPData(connectionId,content);
sendData("AT+CIPCLOSE=0\r\n",1000,DEBUG); //close the connection
delay(10000);
sendData("AT+CIPSERVER=0\r\n",1000,DEBUG); // turn off server
delay(10000);
sendData("AT+CIPSERVER=1,80\r\n",1000,DEBUG); // turn on server on port 80
delay(10000);
}
}
}
Android code :
package com.example.youssefguirat.socketseverywhere;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
Client(String addr, int port,TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
socket.sendUrgentData(16);
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "UnknownHostException: " + e.toString();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response = "IOException: " + e.toString();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/* #Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
textResponse.setText(values[0]);
Toast.makeText(MainActivity.this,"Server:"+values[0], Toast.LENGTH_LONG).show();
Log.w("MSG","Updating with msg");
}*/
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
}
public class MainActivity extends Activity {
Button buttonSend;
TextView textViewSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonSend = (Button) findViewById(R.id.buttonSend);
textViewSocket = (TextView) findViewById(R.id.textViewSocket);
buttonSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Client myClient = new Client("192.168.1.25",80,textViewSocket);
myClient.execute();
}
});
}
}
As you can see, I put a long delay in order to get correct and significant answer from the esp8266 but it didn't work :(busy response when trying to close and configure the server each time I send data
So, can someone help me with it ! I'm really stuck :(
I have an android application which sends and receives UDP packets over WIFI.
the application send data to WIFI modem and then modem response to application by sending UDPpacket.
my app send data perfectly ,but unfortunately I cannot receive data from modem and show it on my screen.
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class UdpConnectionWIFImodemActivity extends Activity {
final String strNetworkIP = "192.168.0.0";
final int intUDP_Port=8080;
private int sourceport=0;
class SocketListener implements Runnable
{
String str;
public void run()
{
DatagramSocket socket;
DatagramPacket packet;
byte[] buf = new byte[256];
System.out.println("Thread running");
if (sourceport!=0) {
try
{
socket = new DatagramSocket(sourceport);
while (true)
{
final TextView t = (TextView) findViewById(R.id.textView1);
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
System.out.println("Received packet");
String s = new String(packet.getData());
CharSequence cs = t.getText();
str = cs + "\r\n" + s;
t.post(new Runnable()
{
public void run()
{
t.setText(str);
}
}
);
}
}
catch (IOException e)
{
Log.e(getClass().getName(), e.getMessage());
}
}
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView tv = (TextView) findViewById(R.id.textView1);
Button send1 = (Button) findViewById(R.id.button1);
send1.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
String s = "1RPMONgetinfo";
try
{
final DatagramSocket socket = new DatagramSocket();
byte[] buf = new byte[256];
buf = s.getBytes();
InetAddress address = InetAddress.getByName(strNetworkIP);
final DatagramPacket packet = new DatagramPacket(buf, buf.length, address, intUDP_Port);
new Thread()
{
public void run()
{
try
{
System.out.println("About to send message");
socket.send(packet);
sourceport = socket.getLocalPort();
System.out.println("Sent message");
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
socket.close();
}
}.start();
}
catch (SocketException e1) {
}
catch (UnknownHostException e2) {
}
}
});
Thread t = new Thread(new SocketListener());
t.start();
}
}
I guess you have already solved your problem long time ago. But your problem seems to be the same as I had. The problem was that I bound the Socket false.
This is how it works for me:
InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getByName(*own IP address as String*), *own portnumber you want to listen to*);
Datagramsocket socket = new DatagramSocket(null);
socket.setReuseAddress(true);
socket.bind(inetSocketAddress);
byte[] message = new byte[4096];
DatagramPacket packet = new DatagramPacket(message, message.length);
socket.receive(packet);
btw: To test if I receive the answer packet on my tablet correctly I used the app: "UDP Sender /Receiver"
I have made a program to send a message from a client to a server(2 android devices), but the message is not being sent.
Here is the code of the client side application:
package com.example.clientphone;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
private EditText ipaddress , textfield;
private Button send;
private String ip , message;
private Socket client;
private PrintWriter printwriter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ipaddress = (EditText)findViewById(R.id.editText1);
textfield = (EditText)findViewById(R.id.editText2);
send = (Button) findViewById(R.id.button1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();// enabling strict mode and setting thread policy
StrictMode.setThreadPolicy(policy);
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = textfield.getText().toString();
ip = ipaddress.getText().toString();// getting ip address
textfield.setText(" ");
try {
client = new Socket(ip, 5200);// ip address is entered over here....
printwriter = new PrintWriter(client.getOutputStream() , true);// getting the outputstream
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (UnknownHostException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
});
}
}
Here is the code for server side application. I have chosen the port 5200 to connect on. I want the user to enter the IP address of the other device and not keep it hard-coded:
package com.example.serverphone;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.*;
public class MainActivity extends ActionBarActivity {
TextView message;
private ServerSocket socket;
private Handler UpdateConversationHandler;
Thread ServerThread = null;
public static final int port = 5200;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (TextView)findViewById(R.id.textView1);
UpdateConversationHandler = new Handler();
this.ServerThread = new Thread(new ServerThread());
this.ServerThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread implements Runnable{
#Override
public void run() {
Socket socket2 = null;
try {
socket = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
while(!Thread.currentThread().isInterrupted()){
try {
socket2 = socket.accept();
BufferedReaderThread commThread = new BufferedReaderThread(socket2);
new Thread(commThread).start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class BufferedReaderThread implements Runnable{
private Socket clientSocket;
private BufferedReader input;
public BufferedReaderThread(Socket clientSocket) {
this.clientSocket = clientSocket;
try {
this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
while(!Thread.currentThread().isInterrupted()){// making sure the thread is not interrupted...
try {
String read = input.readLine();
if(read != null){
UpdateConversationHandler.post(new updateUIConversation(read));
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
class updateUIConversation implements Runnable{
private String msg;
public updateUIConversation(String str){
this.msg = str;
}
#Override
public void run() {
message.setText(message.getText().toString() + msg + "/n");
}
}
}
In your client you are doing network operation on the main thread. Do them in a separate thread. Do not silently supress exceptions and you will see in the log.
new Thread(new Runnable() {
public void run() {
try {
Socket client = new Socket(ip, 5200);
PrintWriter = new PrintWriter(client.getOutputStream() , true);
printwriter.write(message);// writing the message
printwriter.flush();// flushing the printwriter
printwriter.close();// closing printwriter
client.close();// closing client
} catch (Exception x) { Log.e("CLIENT", "Exception " + x); }
}).start();
I am debugging my app on my Galaxy S3 and whenever I monitor the processing .. I notice very high load the app processing . Application processing goes to 80 % sometimes which is incredibly hight
Here is the code:
package com.example.socketclient;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
public class SocketCode extends Activity {
private boolean connected = false;
//private Handler handler = new Handler();
public TextView txt;
int doit=0;
protected SocketCore Conn;
public Button b;
public EditText TextToSend;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_socket_code);
b = (Button)findViewById(R.id.button1);
txt = (TextView)findViewById(R.id.textView1);
TextToSend = (EditText)findViewById(R.id.editText1);
//Conn = new SocketCore(this,txt);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("ErrorButton","Button Pressed Before Toggle"+doit);
doit=1;
Log.e("ErrorButton","Button Pressed "+doit);
}
});
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
public class ClientThread implements Runnable {
Socket socket ;
String finall="",text;
PrintWriter out = null;
BufferedReader in = null;
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName("192.168.0.150");
Log.d("ClientActivity", "C: Connecting...");
socket= new Socket(serverAddr,4444);
connected = true;
while (connected) {
try {
if(doit==1)
{
Log.e("ErrorButton","If");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(TextToSend.getText().toString());
finall="";
while ((text = in.readLine()) != null) {
finall += text;
Log.e("Test","Final: "+finall);
if(text=="quit")
{
socket.close();
}
Log.e("ClientActivity", "After Read "+doit+" "+finall);
break;
}
doit=0;
Log.e("ClientActivity", "Out Of IF "+doit);
runOnUiThread(new Runnable() {
public void run() {
txt.setText(finall);
}
});
}
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
txt.setText("Closed Socket");
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
public void ClientHandler(String Send)
{
try{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket
.getOutputStream())), true);
out.println(Send);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
finall = in.readLine();
txt.setText(finall);
}
catch(IOException e)
{txt.setText("Exception");}
}
}
}
The CPU is doing that because you're running a non-stop loop that keeps feeding runnables into the UI thread, so the CPU keeps under very high load. Instead, I'd recommend that you consider using a push strategy instead of a polling strategy with something like GCM (Google Cloud Messaging), where your app wakes up when your server pushes new data onto the device. If that's not a possible solution, I'd throttle the polling rate to a lower rate and limit it to a few times per minute (or less), using Thread.sleep() periodically in run() to avoid flooding the UI thread with runnables.
Fixed
With using Thread.Sleep(200);
while (connected) {
try {
Thread.sleep(200);
Log.e("ErrorButton","If");
if(doit==1)
{
I am testing socket programming on Android however I am having a problem. The client is basically launched through the main activity with a basic function of sending a message to the server and getting a reply.
the client activity:
package com.test.socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class socketActivity extends Activity implements OnClickListener {
String input;
private EditText et;
private ObjectOutputStream oos;
private TextView tv;
private String message;
private ObjectInputStream ois;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(),7777);
//send to server
oos = new ObjectOutputStream(socket.getOutputStream());
et = (EditText) findViewById(R.id.text);
Button sendButton = (Button) findViewById(R.id.button);
sendButton.setOnClickListener(this);
//read from server
ois = new ObjectInputStream(socket.getInputStream());
//System.out.println("Message from Server: "+message);
tv = (TextView) findViewById(R.id.textView);
}
catch(UnknownHostException e)
{
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId())
{
case R.id.button:
input = et.getText().toString();
try {
oos.writeObject(input);
ois.close();
oos.close();
message = (String) ois.readObject();
tv.setText("Message from Server: "+message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
}
The Server class launched separately from JCreator listening to port 7777:
import java.io.*;
import java.lang.*;
import java.net.*;
public class server {
private ServerSocket server;
private int port = 7777;
public server()
{
try{
server = new ServerSocket(port);
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void main(String args[])
{
server example = new server();
example.handleConnection();
}
public void handleConnection()
{
System.out.println("Waiting for client message...");
while(true)
{
try{
Socket socket = server.accept();
new ConnectionHandler(socket);
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
}
ConnectionHandler class which the Server accesses:
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
public class ConnectionHandler implements Runnable {
private Socket socket;
public ConnectionHandler(Socket socket)
{
this.socket = socket;
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
// TODO Auto-generated method stub
try{
//receive from client
ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
String message = (String) ois.readObject();
System.out.println("Message from client: "+message);
if(message.equals("check"))
{
System.out.println("Checking for malicious interference...");
Thread.sleep(5000);
System.out.println("Status: Files are good.");
}
//send response to client
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
if(message.equals("check"))
{
oos.writeObject("Checking...");
}
else oos.writeObject("Invalid input");
ois.close();
oos.close();
socket.close();
System.out.println("Waiting for client message...");
}
catch(IOException e)
{
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I have tested the code on JCreator and Eclipse through Java application not Android app and it worked perfect. However when I try doing it through the activity, it's not working.
Any ideas?
In Android, localhost would point to the phone/emulator itself. It doesn't point to your server. The following line below is pointing to your Android device/emulator and not your server. You need to get the actual IP of the server to get it working from your Android
InetAddress host = InetAddress.getLocalHost();
Socket socket = new Socket(host.getHostName(),7777);
It works through Java App, because when you execute it from the context of Java Application, the localhost is pointing to the same server location.