using UDP to broadcast on Wifi Direct - android

i'm new to wifi direct and i want to be able to broadcast a message, because i have a timeline and when i click the Post button i want all the connected devices have that message displayed on their timeline. I am able to send data peer to peer.I have searched about this subject and i found using UDP is a good choice but i don't know how to implement it in wifi direct.
I found this code that uses UDP on wifi to Get the Broadcast Address
InetAddress getBroadcastAddress() throws IOException {
WifiManager wifi = mContext.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifi.getDhcpInfo();
// handle null somehow
int broadcast = (dhcp.ipAddress & dhcp.netmask) | ~dhcp.netmask;
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++)
quads[k] = (byte) ((broadcast >> k * 8) & 0xFF);
return InetAddress.getByAddress(quads);}
and this for Sending and Receiving UDP Broadcast Packets
DatagramSocket socket = new DatagramSocket(PORT);
socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(data.getBytes(), data.length(),
getBroadcastAddress(), DISCOVERY_PORT);
socket.send(packet);
byte[] buf = new byte[1024];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
could you please help me and explain to me how it works
thanks in advance.

In Android's Wi-Fi P2P there is a concept of "group owner", which is the device that acts as an access point. For the current API the group owner's IP address seems to be set to 192.168.49.1, which I think is hard-coded somewhere. A quick guess on the broadcast address for the group's network will be 192.168.49.255. For all (of a few) devices I have tested so far that turned out to be the case.

One solution is to Multicast a packet to a Multicast Group. All the devices join a Multicast IP and the sender sends the packet to that Multicast IP. Make sure IP you assign falls in the range of Multicast IPs. When dealing with Multicasting, the device needs to acquire a Multicast Lock. Note that since Multicast is based on UDP, some errors in transmissions are expected.
AsyncTask Class for Devices that will receive the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class ReceiverMulticastAsyncTask extends AsyncTask<Void, Integer ,String > {
#Override
protected String doInBackground(Void... params) {
//Acquire the MulticastLock
WifiManager wifi = (WifiManager) getActivity().getSystemService(Context.WIFI_SERVICE);
MulticastLock multicastLock = wifi.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
//Join a Multicast Group
InetAddress address=null;
MulticastSocket clientSocket=null;
try {
clientSocket = new MulticastSocket(1212);
address = InetAddress.getByName("224.0.0.1");
clientSocket.joinGroup(address);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DatagramPacket packet=null;
byte[] buf = new byte[1024];
packet = new DatagramPacket(buf, buf.length);
//Receive packet and get the Data
try {
clientSocket.receive(packet);
byte[] data = packet.getData();
Log.d("DATA", data.toString()+"");
} catch (Exception e) {
e.printStackTrace();
}
multicastLock.release();
try {
clientSocket.leaveGroup(address);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
clientSocket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever...
}
}
AsyncTask Class for Device that will send the packet:
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.SocketException;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.MulticastLock;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
public class SenderMulticastAsyncTask extends AsyncTask<Void, Integer, String> {
#Override
protected String doInBackground(Void... params) {
int port =1212;
DatagramSocket socket=null;
try {
socket = new DatagramSocket(port);
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InetAddress group = null;
try {
group = InetAddress.getByName("224.0.0.1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
//Sending to Multicast Group
String message_to_send ="Test";
byte[] buf = message_to_send.getBytes();
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
try {
socket.send(packet);
Log.d("Send", "Sending Packet");
} catch (IOException e) {
// TODO Auto-generated catch block
socket.close();
e.printStackTrace();
}
socket.close();
return "";
}
#Override
protected void onPostExecute(String result) {
//do whatever ...
}
}

Related

java.net.ConnectException: Connection refused: connect

My problem when I try to send a simple "hello world" msg from the pc "client " to the phone "server " and
I tried all possible solution like : starting the server app which is on the phone first then the client but didn't work,
I changed the ip address too but didn't work,
I closed the firewall nothing happened too
Server's code:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);}
public class Server{
public void main(String args[]) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(5000);} catch (IOException e) {
e.printStackTrace();
}
while (true) {
// Wait for a client connection.
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
e.printStackTrace();
}
// Create and start a thread to handle the new client
try {
// Get the socket's InputStream, to read bytes
// from the socket
InputStream in = clientSocket.getInputStream();
// wrap the InputStream in a reader so you can
// read a String instead of bytes
BufferedReader reader = new BufferedReader(
new InputStreamReader(in, Charset.forName("UTF-8")));
// Read from the socket and print line by line
String line;
while ((line = reader.readLine()) != null) {
Toast.makeText(getApplicationContext(),line,Toast.LENGTH_LONG).show();
}
}
catch (IOException e) {
e.printStackTrace();
} finally {
// This finally block ensures the socket is closed.
// A try-with-resources block cannot be used because
// the socket is passed into a thread, so it isn't
// created and closed in the same block
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}}
Client's code:
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
public class ClientClass {
public static void main(String args[]) {
try (Socket socket = new Socket("192.168.1.3", 5000);) {
// We'll reach this code once we've connected to the server
// Write a string into the socket, and flush the buffer
OutputStream outStream = socket.getOutputStream();
PrintWriter writer = new PrintWriter(
new OutputStreamWriter(outStream, StandardCharsets.UTF_8));
writer.println("Hello world!");
writer.flush();
} catch (IOException e) {
// Exception should be handled.
e.printStackTrace();
}
}
}
error:
java.net.ConnectException: Connection refused: connect
at java.net.DualStackPlainSocketImpl.connect0(Native Method)
at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:79)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at java.net.Socket.connect(Socket.java:538)
at java.net.Socket.<init>(Socket.java:434)
at java.net.Socket.<init>(Socket.java:211)
at ClientClass.main(ClientClass.java:10)
BUILD SUCCESSFUL (total time: 2 seconds)
I was having same error, and i managed to know what causes this error in my case, you have to check two things:
1-Router configuration if you are connected using WiFi because you have to forward your port correctly.(How to Set Up Port Forwarding on a Router, it differs according to router type)
2-If this IP address here is the correct IP address of your mobile or not:
Socket socket = new Socket("192.168.1.3", 5000);
(How To Check Your Android IP Address)
In the MainActivity class, the inner class named Server is never instantiated and the "main" method is neither called too.
Please have a look to this Tutorial post so as to have an example of how to implement a server using sockets with android devices.

Unable to read data (send by server) at Client Side

I am trying to develop an app in which
1.client sends request to server for connection(IP address+PORT no.)+sends data using "PrintStream"+Tries to read the data from Server(Using Inputstream)
2.Client creates the socket.
3.Server reads the data send by Client
4.SERVER writes the data using "PrintStream" at same time point no 3.
Problem is at point 4 Data written by SERVER is not Read by "INPUTSTREAM" of client(Point 1)
I dont know these Simultaneous operation are possible or not.If possible then how.If not then what is the alternate way?
Server Code
package com.example.loneranger.ser;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
public class MainActivity extends Activity {
TextView ip;
TextView msg;
String data = "";
ServerSocket httpServerSocket;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ip = (TextView) findViewById(R.id.infoip);
msg = (TextView) findViewById(R.id.msg);
ip.setText(getIpAddress() + ":"
+ 8080 + "\n");
Server server = new Server();
server.start();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (httpServerSocket != null) {
try {
httpServerSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private String getIpAddress() {
String ip = "";
try {
Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
.getNetworkInterfaces();
while (enumNetworkInterfaces.hasMoreElements()) {
NetworkInterface networkInterface = enumNetworkInterfaces
.nextElement();
Enumeration<InetAddress> enumInetAddress = networkInterface
.getInetAddresses();
while (enumInetAddress.hasMoreElements()) {
InetAddress inetAddress = enumInetAddress.nextElement();
if (inetAddress.isSiteLocalAddress()) {
ip += "IP: "
+ inetAddress.getHostAddress() + "\n";
}
}
}
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
ip += "Something Wrong! " + e.toString() + "\n";
}
return ip;
}
private class Server extends Thread {
#Override
public void run() {
Socket socket = null;
try {
httpServerSocket = new ServerSocket(8888);
while(true){
socket = httpServerSocket.accept();
HttpResponseThread httpResponseThread =
new HttpResponseThread(
socket);
httpResponseThread.start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private class HttpResponseThread extends Thread {
Socket socket;
HttpResponseThread(Socket socket){
this.socket = socket;
}
#Override
public void run() {
BufferedReader BReader;
PrintWriter printer;
String request;
try { InputStream inputStream = socket.getInputStream();
BReader = new BufferedReader(new InputStreamReader(inputStream));
request = BReader.readLine();
Thread.sleep(500);
printer = new PrintWriter(socket.getOutputStream(), true);
printer.print("hello laundu");
printer.flush();
String ip123=socket.getInetAddress().toString();
printer.close();
BReader.close();
socket.close();
data += "Request of " + request
+ " from "+ ip123 + "\n";
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
msg.setText(data);
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return;
}
}
}
Client Code
mport android.os.AsyncTask;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
public class Client extends AsyncTask<Void, Void, Void> {
String dstAddress;
int dstPort;
String response = "";
TextView textResponse;
MainActivity activity;
OutputStream outputStream;
BufferedReader BReader;
String request;
Client(String addr, int port, TextView textResponse) {
dstAddress = addr;
dstPort = port;
this.textResponse=textResponse;
this.activity=activity;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(dstAddress, dstPort);
Server server = new Server(socket);
server.start();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.print("futfujb");
out.flush();
/*
* notice: inputStream.read() will block if no data return
*/
} 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 {
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
return null;
}
#Override
protected void onPostExecute(Void result) {
textResponse.setText(response);
super.onPostExecute(result);
}
private class Server extends Thread {
Socket socket;
Server(Socket socket)
{
this.socket=socket;
}
#Override
public void run() {
try { //Thread.sleep(500);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(
1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
if(inputStream.available()>0)
{
while ((bytesRead = inputStream.read(buffer)) != -1) {
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString("UTF-8");
}
}
inputStream.close();
socket.close();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
As I commented above, there is nothing in this code that corresponds to either of these steps:
2.Server gets the request creates new SOCKET connection.
(a) There is no request, and (b) the server does not create a new connection. The client creates it. The server accepts it.
3.Server reads the data send by Client.
The client doesn't send any data.
There are two problems here (at least):
The server is blocking in readLine() waiting for a message that the client never sends. So it never gets to its own send, so nothing is received by the client. Have the client send a request, as per the comments.
The client is incorrectly using available(). Remove this test and let the client fall through into the read loop. It will exit that when the peer (the server) closes the connection.

Sending and Receiving UDP packets on datagram socket in android

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"

Sending SMS data from broadcastreceiver to a python server over a TCP Socket

I have a broadcast receiver set up to listen for any SMS Received. I want to send this data over a socket back to a python server I have running on my local machine. I've set up a Toast notification to prove to my self that the broadcast receiver works whenever it receives a SMS. Before i added the sending data over a socket the toast would appear inside or outside the application, but after adding the socket portion the toast not only does the data not get sent over the socket but the toast doesn't show up either.
Here is my SMSReciever.java
import java.net.Socket;
import java.net.UnknownHostException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
public class SMSReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
Object messages[] = (Object[]) bundle.get("pdus");
SmsMessage smsMessage[] = new SmsMessage[messages.length];
for (int n = 0; n < messages.length; n++) {
smsMessage[n] = SmsMessage.createFromPdu((byte[]) messages[n]);
}
//---"From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody();
// show first message
Toast toast = Toast.makeText(context, "From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody(), Toast.LENGTH_LONG);
toast.show();
Socket socket;
try {
socket = new Socket("10.0.2.2", 7000);
OutputStream out = socket.getOutputStream();
PrintWriter output = new PrintWriter(out);
output.println("Hello from Android");
out.flush();
out.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try{
Socket socket = new Socket("10.0.2.2",7000);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
DOS.writeUTF("From: " +smsMessage[0].getDisplayOriginatingAddress() + " Text: " + smsMessage[0].getDisplayMessageBody());
socket.close();
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
*/
}
}
and here is the python server which listens for connection and prints out the data recieved onto the terminal
server.py
from socket import *
HOST = "127.0.0.1" #local host
PORT = 7000 #open port 7000 for connection
s = socket(AF_INET, SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(2) #how many connections can it receive at one time
print "Server started at 127.0.0.1:7000"
conn, addr = s.accept() #accept the connection
print "Connected by: " , addr #print the address of the person connected
while True:
data = conn.recv(5084) #how many bytes of data will the server receive
print "Received: ", repr(data)
conn.close()

Android Socket Thread Add very high load at processor

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)
{

Categories

Resources