Android run code in Service all the time - android

I want to create a Service that runs in the background and checks if the client sends a message to the server and answers to it.
Here's what I tried so far:
package com.server.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class ServerService extends Service {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStreamReader inputStreamReader;
private static BufferedReader bufferedReader;
private static String message;
Thread serverThread;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
System.out.println("hello1");
Toast.makeText(this, "Server Started", Toast.LENGTH_LONG).show();
serverThread = new Thread(new Runnable() {
public void run() {
try {
System.out.println("hello2");
try {
serverSocket = new ServerSocket(4444);
} catch (IOException e) {
System.out.println("Could not listen on port: 4444");
}
System.out.println("Server started. Listening to the port 4444");
while (true) {
System.out.println("hello3");
try {
clientSocket = serverSocket.accept();
inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
message = bufferedReader.readLine();
System.out.println(message);
inputStreamReader.close();
clientSocket.close();
} catch (IOException ex) {
System.out.println("Problem in message reading");
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
serverThread.start();
}
}
The problem is, that when the code is in onCreate(), it only gets executed when the service gets created, and I want it to run all the time. So where do I have to put the code in the Service class so it runs all the time?
Best Regards,
Alex

Related

AsyncTask not executing multiple times

I have an app which has to poll a TCP server (on LAN) to fetch some data, I'm doing this using sockets in an AsyncTask class.
It works well for the first few requests. But at a certain point, the app must poll the server every 2s (using a timer). This is when the AsyncTask stops executing and the TCP messages do not get sent to the server. I can't figure out why.
Code is below. Any help will be appreciated!
Thank you!
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
public class TcpTask extends AsyncTask<String, Void, String> {
Context context;
TcpResultListener tcpResultListener;
int actionCode;
String TAG = "TcpTask";
String SERVER_IP = "192.168.1.12", SERVER_PORT = "1234";
Socket socket = null;
PrintWriter out;
int readTimeout;
// Creating listener
public void setOnTcpResultsListener(TcpResultListener tcpResultListener, int actionCode) {
this.tcpResultListener = tcpResultListener;
this.actionCode = actionCode;
}
// Constructor with context as parameter
public TcpTask(Context context, int timeout) {
this.context = context;
this.readTimeout = timeout;
}
#Override
protected String doInBackground(String... params) {
String result = null;
try {
//Create a client socket and define internet address and the port of the server
socket = new Socket(params[0], Integer.parseInt(params[1]));
Log.d(Constants.TAG, "Socket created");
//Setting timeout for readLine
socket.setSoTimeout(readTimeout);
Log.d(Constants.TAG, "Timeout set");
//Get the output stream of the client socket
out = new PrintWriter(socket.getOutputStream(), true);
Log.d(Constants.TAG, "PrinterWriter created");
//Write data to the output stream of the client socket
out.println(params[2]);
Log.d(Constants.TAG, "Sending TCP data: " + params[2]);
//Get the input stream of the client socket
InputStream is = socket.getInputStream();
//Buffer the data coming from the input stream
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//Read data in the input buffer
result = br.readLine();
} catch (NumberFormatException e) {
Log.d("TcpException", e.toString());
} catch (UnknownHostException e) {
Log.d("TcpException", e.toString());
} catch (IOException e) {
Log.d("TcpException", e.toString());
}
try {
Log.d(Constants.TAG, "Socket:: " + socket);
if(socket != null){
socket.close();
}
} catch (IOException e) {
Log.d(Constants.TAG, e.toString());
}
return result;
}
#Override
protected void onPostExecute(String result) {
Log.d(Constants.TAG, "String:: " + result);
tcpResultListener.onResultsReceived(result, actionCode);
}
}
The method I use to call the AsyncTask:
void sendTCP(String msg) {
TcpTask tcpTask = new TcpTask(this, 8000);
// Setting listener for tcpTask to send back result
tcpTask.setOnTcpResultsListener(AddSpaceActivity.this, 1);
// TODO: Change the data being passed below
//Pass the server ip, port and client message to the AsyncTask
tcpTask.execute(gwIP, gwPort, msg);
}
EDIT: Timer code:
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
Log.d(Constants.TAG, "Timer fired:: " + firstReceived);
if(firstReceived){
sendTCP(Constants.NETWORK_STATUS_REQUEST);
}
}
}, 3000, 2000);

Android Socket Programming Delay

I have a client android app and a server program on PC. In client app, I start a new thread in onCreate() of my Activity. In that thread, there is an infinite loop which sends message to the server. But there is sometimes a delay of up to 5 seconds. Here is the code of client side:
EDIT
new Thread(new Runnable() {
public void run() {
Socket socket = null;
PrintWriter out = null;
try {
socket = new Socket(ip, 1755);
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException e) {
e.printStackTrace();
}
while(true) {
if(socket != null) {
out.println(msg);
}
}
}
}).start();
Now the message is not being delivered.
Refer this code ,
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* #author Krish
*/
public class Client {
public void connect() {
new Thread(new ClientThread()).start();
}
public void disconnect() {
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendMessage(String msg) {
try {
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(msg);
} catch (IOException e) {
e.printStackTrace();
}
}
private Socket socket;
class ClientThread implements Runnable {
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.0.2.15";
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
And also find optimization techniq
Could be because you are creating infinite amount of sockets and sending. Rather than creating once and sending then closing or could be a network issue.

How to get message to send from server to Android

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();

Android Client-server message exchanging is slow

I have a working messaging app that sends messages from the client to the server.
I want the client to CONSTANTLY listen for messages from the server.
I want the client to only send packets to the server when "Start" is called, but the problem is that I have to press it twice for the message to actually deliver to the server (Idk why)
Later on I'll change the program to something that always delivers messages to the server (his GPS location), so I would also like some tips about how to make a loop in an Android app.
//Client
package com.example.clienttest;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
Thread m_objThreadClient;
Socket clientSocket;
TextView serverMessage;
EditText clientMessage;
String sIn, sOut;
BufferedReader brOut, brIn;
DataOutputStream oos;
DataInputStream ois;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage = (TextView) findViewById(R.id.textView1);
clientMessage = (EditText) findViewById(R.id.editText1);
m_objThreadClient = new Thread( new Runnable(){
public void run()
{
try {
clientSocket = new Socket("192.168.1.102", 4000);
oos = new DataOutputStream (clientSocket.getOutputStream());
ois = new DataInputStream (clientSocket.getInputStream());
brIn = new BufferedReader (new InputStreamReader(ois));
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
});
m_objThreadClient.start();
}
public void Listener(){
try {
while ((sIn = brIn.readLine()) != null){
sIn = brIn.readLine();
}
serverMessage.setText(sIn);
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void Start(View view) {
sOut = clientMessage.getText().toString();
try {
oos.writeUTF(sOut);
oos.flush();
oos.flush();
} catch (IOException e) {
serverMessage.setText(e.getMessage());
}
}
public void onStop(){
try {
oos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//Server
import java.net.ServerSocket;
import java.net.Socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.util.Hashtable;
public class Server2 {
#SuppressWarnings("resource")
public static void main (String[] args) throws IOException {
ServerSocket server = null;
try {
server = new ServerSocket(4000);
} catch (IOException e) {
System.err.println("Could not start up on: " + "4000" + "Maby server is already open? Or a portforwording messup?");
System.err.println(e);
System.exit(1);
}
Socket client = null;
while(true) {
try {
client = server.accept();
System.out.print("Connected ");
} catch (IOException e) {
System.err.println("Accept failed.");
System.err.println(e);
}
Thread t = new Thread(new ClientConn(client));
t.start();
}
}
}
class ClientConn implements Runnable {
private Socket client;
String Recv;
DataInputStream inFromClient;
DataOutputStream outToClient;
ClientConn(Socket client) {
this.client = client;
try {
inFromClient = new DataInputStream(client.getInputStream());
outToClient = new DataOutputStream(client.getOutputStream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
String response;
try {
while ((response = inFromClient.readUTF()) != null) {
Recv = inFromClient.readUTF();
System.out.print("Msg: " + Recv + " \n");
if( Recv.equals("Hi")){
outToClient.writeUTF("Wa alaikum");
outToClient.flush();
}
else{
outToClient.writeUTF("..what?");
outToClient.flush();
}
}
} catch (IOException e) {
System.out.print("No input ");
System.err.println(e);
}
}
}

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