public static boolean SendMessage(final String response)
{
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out,response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun=true;
return false;
}
return true;
here is my code for sending login message to tcp socket. I want to perform an asynchronous task for this activity. How can i do that.
try code like this and execute new MyAsync().execute(); whenever you want send sms
public class MyAsync extends AsyncTask<Void, Void, Boolean> {
#Override
protected Boolean doInBackground(Void... params) {
return SendMessage(response);
}
}
public static boolean SendMessage(final String response) {
OutputStream out;
try {
out = socket.getOutputStream();
writeResponse(out, response);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mRun = true;
return false;
}
return true;
}
Related
I am using an asynctask while I am doing some telnet operations. However, the progressdialog is not shown, and I am almost 100% sure that Telnet is the cause.
Please take a look to my code and help me to find where is the problem.
Thanks
public class TelnetManager extends AsyncTask<String, Void, String>{
private TelnetClient telnet;
private int port;
private String IP;
private ProgressDialog dialog;
private Context context;
public TelnetManager(Context c,String IP, int port, String user, String pass)
{
context=c;
this.IP=IP;
this.port=port;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog=new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.msg_wait));
dialog.show();
}
public String readString() throws IOException
{
InputStream in = new BufferedInputStream(telnet.getInputStream());
int read=0;
String s=null;
do
{
byte[] buffer = new byte[1024];
read = in.read(buffer);
if(read > 0)
{
if(s==null)s=new String(buffer, 0, read);
else s+=new String(buffer, 0, read);
Log.e("S",s);
}
}
while (read > 0);
in.close();
return s;
}
public void writeString(String command) throws IOException
{
OutputStream out = telnet.getOutputStream();
OutputStreamWriter writer = new OutputStreamWriter(out,"UTF-8");
writer.write(command+'\n');
writer.flush();
}
#Override
protected String doInBackground(String... params) {
telnet = new TelnetClient();
String s="";
try {
telnet.setConnectTimeout(10000);
telnet.connect(IP,port);
telnet.setKeepAlive(true);
writeString("password");
writeString(params[0]);
writeString("exit");
String aux=readString();
telnet.getInputStream().close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
telnet.disconnect();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if(dialog!=null && dialog.isShowing())
{
dialog.dismiss();
}
}
}
And here is where I call the AsyncTask:
String list=null;
try {
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("son").get();
construirLayout(list,R.id.containerON);
list=new TelnetManager(this,"192.168.11.30", 10010, null, null).execute("soff").get();
construirLayout(list,R.id.containerOFF);
}
catch (InterruptedException e) {
Toast.makeText(this,"InterruptedException",3000).show();
e.printStackTrace();
}
catch (ExecutionException e) {
Toast.makeText(this,"ExecutionException",3000).show();
e.printStackTrace();
}
If you call get() on an AsyncTask, you're telling the UI thread to block and wait for the AsyncTask results. Since the UI thread is blocked, it cannot show the ProgressDialog.
You should instead provide a callback to the AsyncTask, to be fired in onPostExecute().
I'm using a TimerTask to get the result of a Wi-Fi scan on a specific interval. I want to send the scanning results to a server.So I used AsyncTask to send the results. When I call the AsyncTask from inside the TimerTask my application crashes. Can anyone tell me why this is happening? Also in my code what is the best way to send the result to a server?
Here is my code:
public class ServerComm extends AsyncTask<String, Void, String>{
int port=9999;
String IP="192.168.2.100";
BufferedReader input;
#Override
protected String doInBackground(String... scanRes) {
// TODO Auto-generated method stub
Socket socket;
String loc="";
FileWriter writer;
File sock=new File(Environment.getExternalStorageDirectory()+"/network.txt");
try {
writer = new FileWriter(sock, true);
writer.append("in async task.\n");
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
InetAddress serverAddr = InetAddress.getByName(IP);
socket = new Socket(serverAddr, port);// socket is created
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("ser","socket");
// now send
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
out.println(scanRes);
// get the reply
loc = input.readLine();
//close
socket.close();
return loc;
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return loc;
}
#Override
protected void onPostExecute(String result) {
// draw the new location on the map
}
This is the code of the TimerTask:
public void Locate()
{
if(isScanning)// if a previous scan is running cancel it
{
timer.cancel();
}
else
{
timer.schedule(new TimerTask() { // start new scanner
#Override
public void run() {
// TODO Auto-generated method stub
if(counter==numOfScans)
{
try {
writer = new FileWriter(file, true);
writer.append(RSS+" \n");
writer.append("Finished Collecting RSSIs.\n");
writer.close();
new ServerComm().execute(RSS);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
timer.cancel();
}
else // not finished
{
isScanning=true;
if(result!=null)
{
if(result.size()!=0)
{
for(int i=0;i< result.size();i++)
{
RSS=RSS+result.get(i).BSSID+" "+result.get(i).level+" ";
}//end for
counter++;
} // end of if
}//end of else
}
}
}, 0,Interval);
}
//get location
}
I solved the problem, so I'm posting the answer in case someone else faced the same problem.
The problem was the AsyncTask should not be called from TimerTask. A handler should be used to run the AsyncTask Like this:
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
public void run() {
new ServerComm().execute(RSS);
}
});
This is solution is by arthvading on this question.
I am sending image using Socket Server and Client. It gived me dialog "App not responding" i think beacuse converting this bitmap was making in UiThread. So i tried to change it but i am still getting this message "App is not responding". It's happening when i am sending big imaes +500kb.
Here is my code for Server:
public class SocketServerThread extends Thread {
static final int SocketServerPORT = 8080;
int count = 0;
#Override
public void run() {
try {
serverSocket = new ServerSocket(SocketServerPORT);
while (true) {
Socket socket = serverSocket.accept();
count++;
// Here where i am doing my code i think is not doing in UiThread..
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run()
{
// Firstly i was doing my code here...
}
});
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My code for client:
public class MyClientTask extends AsyncTask<Void, Void, Void> {
MyClientTask(String addr, int port){
dstAddress = addr;
dstPort = port;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try
{
//I am sending my image here...
}
}
} 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 onPostExecute(Void result)
{
super.onPostExecute(result);
}
}
So please help my . Why still i am getting not responding dialog?
The ANR error code happens when you block the UI thread more than 5 seconds. If you need to do background work don't use the main thread. Receive the data in a separate thread and post only the result to the UI thread.
i've done an application in which the android application send datas to java desktop swing application as well as send datas from desktop to android using TCP socket programming through wifi.
Th application is a Hotel Kitchen order booking system
The problem describes that Dine_Tables class contains buttons which represents each tables in a hotel, on clicking table1 button for example it starts the BackgroundServers Asyntask which runs a server for receiving desktop application datas also it takes the activity from Dinein_Tables.java to Food_Customizer.java.
In Food_Customizer.java on clicking submit button it starts ServersendAsyncAction Asyntask which sends some datas to desktop swing application.
The desktop application after processing sends some datas to android application, The server that runs in the android application on receiving the datas goes again from Food_Customizer.java to Dinein_Tables.java activity in the BackgroundServers Asyntask onPostExecute method.
The problem is that when i do this process a two or three times the application stop due to address-in use and Null-Pointer exception at socket = serverSocket.accept(); in the BackgroundServers Asyntask.
Can anyone please tell me some solution for this problem
Dinein_Tables.java
public class Dinein_Tables extends Activity {
:
:
table1.setOnClickListener(new OnClickListener() {
public void onClick(final View v) {
new Handler().postDelayed(new Runnable() {
public void run() {
Food_Customizer.BackgroundServers ob = new Food_Customizer().new BackgroundServers(contexts);
ob.execute("");
Intent toAnotherActivity = new Intent(v.getContext(), Food_Customizer.class);
startActivity(toAnotherActivity);
finish();
}
}, 100L);
}
});
}
Food_Customizer.java
public class Food_Customizer extends Activity {
:
:
submit= (Button)findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pd = ProgressDialog.show(contexts, "Sending to Server...","Please Wait...", true, false);
new ServersendAsyncAction().execute();
}
});
:
:
/****************************** AsyncTask ********************************************************/
private class ServersendAsyncAction extends AsyncTask<String, Void, String> {
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
boolean flag = true;
while (flag) /******** If data is send flag turn to be false *******/
{
try {
socket = new Socket("192.168.1.74", 4444);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(datastosend);
flag = false;
} catch (UnknownHostException e) {
flag = true;
e.printStackTrace();
} catch (IOException e) {
flag = true;
e.printStackTrace();
}
/******** CLOSING SOCKET *****************/
finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAOUTPUTSTREAM *******/
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/******** CLOSING DATAINPUTSTREAM ********/
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
protected void onPostExecute(String result) {
}
/********************* ENDING OF ASYN TASK CLASS ServersendAsyncAction ***************************/
}
public Context con;
public static ServerSocket serverSocket = null;
public class BackgroundServers extends AsyncTask<String, Void, String> {
public BackgroundServers(Context context) {
con=context;
}
/****************************** AsyncTask doInBackground() ACTION ********************************/
protected String doInBackground(String... args) {
Socket socket = null;
DataInputStream dataInputStream = null;
DataOutputStream dataOutputStream = null;
try {
serverSocket = new ServerSocket(9999);
System.out.println("Listening :9999");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while (true) {
try {
socket = serverSocket.accept();
dataInputStream = new DataInputStream(
socket.getInputStream());
dataOutputStream = new DataOutputStream(socket.getOutputStream());
System.out.println("ip: " + socket.getInetAddress());
String incoming_message=(dataInputStream.readUTF());
incoming_message=incoming_message.replace("/", "");
String recdatas[]=incoming_message.split("#");
if(recdatas[0].equalsIgnoreCase("success"))
{
DatabaseConnection dbs=new DatabaseConnection(con);
int status=dbs.update("UPDATE hotel_pub_tables SET status='occupied' WHERE tableno='"+recdatas[1]+"'");
if(status>0)
{
tabelstatus=1;
//msg.obj="Table status changed!!!";
System.out.println("Table status changed!!!");
if (true) {
System.out.println("entered 222");
System.out.println(tabelstatus);
if(tabelstatus==1)
{
System.out.println(tabelstatus);
Food_Customizer.pd.dismiss();
System.out.println("success");
}
else if(tabelstatus==2)
{
Food_Customizer.pd.dismiss();
Intent intent = new Intent(Food_Customizer.this, Dinein_Tables.class);
startActivity(intent);
finish();
}
}
}
else
tabelstatus=2;
dbs.close();
}
dataOutputStream.writeUTF("Hello!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (socket != null) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataInputStream != null) {
try {
dataInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (dataOutputStream != null) {
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return null;
}
/******** returns what you want to pass to the onPostExecute() *******/
}
/****************************** AsyncTask onPostExecute() ACTION *********************************/
#Override
protected void onPostExecute(String result) {
System.out.println("eneterd on posttttttttttttttt");
con.startActivity(new Intent(con, Dinein_Tables.class));
finish();
}
}
}
/********************* ENDING OF ASYN TASK CLASS BackgroundServers ***************************/
}
Well it's obvious that you setup your server on port 9999:
serverSocket = new ServerSocket(9999);
But you connect with the server on port 4444:
socket = new Socket("192.168.1.74", 4444);
Make sure you connect to the correct port-number otherwise it wont work. Hope this helps.
I have a simple connection activity:
package com.example.conn08;
import ...;
public class MainActivity extends Activity
{
public static Socket clientSocket;
public static DataOutputStream outToServer;
public static PrintWriter outTest;
public static BufferedReader inToServer;
With PrintWriter outTest I test server's availability:
If the user has no Internet, or the server doesn't work, I put Thread on a pause with Boolean shouldContinue.
private Thread mThread;
private final Object lock = new Object();
private Boolean shouldContinue = true;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThread = new Thread(new Runnable()
{
public void run()
{
while (true)
{
synchronized(lock)
{
try
{
lock.wait(); // lock the Thread
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
while (shouldContinue)
{
try
{
final String data = inToServer.readLine();
if (data != null)
{
Log.v("data", data);
runOnUiThread(new Runnable()
{
#Override
public void run()
{
String put[] = data.split("#");
//Data parsing
}
});
}
}
catch (IOException e)
{
e.printStackTrace();
}
Check on availability of the server:
try {
if(clientSocket.getInputStream().read() == -1)
{
Log.v("Connection: ", "lost");
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
});
mThread.start();
Connect();
}
public void Connect()
{
shouldContinue = true;
try
{
clientSocket = new Socket();
clientSocket.connect(new InetSocketAddress("localhost", 15780), 30000);
outToServer = new DataOutputStream(clientSocket.getOutputStream());
inToServer = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
outTest = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(clientSocket.getOutputStream())), true);
synchronized(lock)
{
lock.notify();
}
sendUTF("3#kokoko"); //send the message!
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void sendUTF(String str)
{
try
{
byte[] buf = str.getBytes("UTF-8");
outToServer.write(buf, 0, buf.length);
outToServer.writeBytes("\n");
outToServer.flush();
}
catch (IOException e)
{
e.printStackTrace();
outServ.setText("Нет соединения!");
}
}
}
Problem in that when I don't use the
if(clientSocket.getInputStream().read() == -1)
And send data to server like here:
sendUTF("3#kokoko");
All is fine, but if I use it, on server I see this message like
"#kokoko" - I lose the first character of the message and my socket is crushed! Help me please