UDP with android - android

why UDP Android just once send [Please Help]
name class MainActivity
public class MainActivity extends Activity implements
android.view.View.OnClickListener {
public static final String SERVERIP = "192.168.5.255";
public static final int SERVERPORT = 4444;
public TextView text1;
public EditText input;
public Button btn;
public boolean start;
public Handler Handler;
conntection with pc
this method on create
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text1 = (TextView) findViewById(R.id.textView1);
input = (EditText) findViewById(R.id.editText1);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(this);
start = false;
new Thread(new Server()).start();
try {
Thread.sleep(500);
} catch (InterruptedException e) {
}
new Thread(new Client()).start();
Handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String text = (String) msg.obj;
text1.append(text);
}
};
}
this class Client
#SuppressLint("NewApi")
public class Client implements Runnable {
#Override
public void run() {
while (start == false) {
}
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
updatetrack("Client: Start connecting\n");
DatagramSocket socket = new DatagramSocket();
byte[] buf;
if (!input.getText().toString().isEmpty()) {
buf = input.getText().toString().getBytes();
} else {
buf = ("Default message").getBytes();
}
DatagramPacket packet = new DatagramPacket(buf, buf.length,
serverAddr, SERVERPORT);
updatetrack("Client: Sending ‘" + new String(buf) + "’\n");
socket.send(packet);
updatetrack("Client: Message sent\n");
updatetrack("Client: Succeed!\n");
} catch (Exception e) {
updatetrack("Client: Error!\n");
}
}
}
this class Client
public class Server implements Runnable {
#Override
public void run() {
while (start = false) {
try {
InetAddress serverAddress = InetAddress.getByName(SERVERIP);
updatetrack("nServer: Start connectingn");
DatagramSocket socket = new DatagramSocket(SERVERPORT,
serverAddress);
byte[] buffer = new byte[17];
DatagramPacket packet = new DatagramPacket(buffer,
buffer.length);
updatetrack("Server: Receivingn");
socket.receive(packet);
updatetrack("Server: Message received:"
+ new String(packet.getData()) + "'n");
updatetrack("Server : Succed!n");
} catch (Exception e) {
updatetrack("Server: Error!n" + e.getMessage());
}
}
}
}
public void updatetrack(String s) {
Message msg = new Message();
String textTochange = s;
msg.obj = textTochange;
Handler.sendMessage(msg);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == R.id.button1)
start = true;
}
}
if i make my class server with
while (true){
application is error
help me please ? why just once send message Thanks before

For Client class, you have nothing in the loop:
while (start == false) {
}
And then outside of it, you call send only once -- that is why it is sending only once.
socket.send(packet);
If you want to call send continuously, then one way to do is to keep it in a loop. Of course, you would need to terminate the loop once the task is done but that would be driven by your application logic.

Related

TextToSpeech stops working after a few hours

I'm trying to make an app reading a string coming from a socket connection, but after a few hours the app stops talking (without exceptions). I'm sure the app is still running because the server sending the string continues to detect the response echo after sending it.
public class MainActivity extends AppCompatActivity {
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ITALY);
}
}
});
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
#Override
public void onDestroy() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
}
super.onDestroy();
}
private class SocketThread extends Thread {
static final int socketPort = 3333;
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(socketPort);
try {
while(true) {
Socket clientSocket = serverSocket.accept();
try {
new ServerThread(clientSocket);
} catch(IOException e) {
clientSocket.close();
} }
}
catch (IOException e) {
}
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
class ServerThread extends Thread {
private int counter = 0;
private int id = ++counter;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
public ServerThread(Socket s) throws IOException {
socket = s;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
out = new PrintWriter(new BufferedWriter(osw), true);
start();
}
public void run() {
try {
while (true) {
String str = in.readLine();
textToSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
}
} catch (IOException e) {}
try {
socket.close();
} catch(IOException e) {}
}
}
}
}
TextToSpeech instance will be available after connect to system service, not after invoke constructor.
So, your plan need to edit like this:
Call TextToSpeech constructor.
Check your TextToSpeech instance is finish to connect to system service through TextToSpeech.OnInitListener.onInit().
Then, connect to your custom service.
Try this as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR) {
int res = textToSpeech.setLanguage(Locale.ITALY);
if (res >= TextToSpeech.LANG_AVAILABLE) {
// TextToSpeech instance is available after connect to system service!
Thread socketT = new Thread(new SocketThread());
socketT.start();
}
}
}
});
// At this time, your TextToSpeech instance may be not available yet.
//Thread socketT = new Thread(new SocketThread());
//socketT.start();
}

Java server- Android socket connection

My goal is to create Java application which would be server, and Android(client) socket connection, and make Android phone listen to my commands send from a server. My question is, how should i make my Android phone always listen for incoming commands(Strings) pushed from Java application. What is a best choice ? Thread, Service ?
Here is my code : Server in java:
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeObject("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
Android Client code:
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
DataOutputStream os;
public final String TAG = "CLIENT";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
ConnectThread thread = new ConnectThread();
thread.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class ConnectThread extends AsyncTask<String, String, String> {
public ConnectThread() {
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
Log.i(TAG,"Do in background");
return connect();
}
public String connect() {
try {
Log.i(TAG," creating socket");
socket = new Socket("192.168.1.10", 9000);
Log.i(TAG," socket created");
os = new DataOutputStream(socket.getOutputStream());
is = new DataInputStream(socket.getInputStream());
Log.i(TAG," Streams are set");
Log.i(TAG,"::"+is.readUTF().toString());
text.setText(is.readLine().toString());
return is.readLine().toString();
} catch (UnknownHostException e) {
e.printStackTrace();
Log.d("fail", e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("fail", e.toString());
}
return "nothing";
}
}
}
I have solved my problem. Im sending messages from my java server to android trough a socket, and android is always listening. Here is my code:
Java :
public class Server extends JFrame {
private JTextField userText;
private JTextArea chatWindow;
private ObjectOutputStream output;
private ObjectInputStream input;
// private DataInputStream input;
private Socket connection;
ServerSocket server;
public Server() {
super("GUI");
userText = new JTextField();
userText.setEditable(false);
userText.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
sendMessage(e.getActionCommand());
userText.setText("");
}
});
add(userText, BorderLayout.NORTH);
chatWindow = new JTextArea();
add(new JScrollPane(chatWindow), BorderLayout.CENTER);
setSize(300, 150);
setVisible(true);
}
// connect to server
public void startRunning() {
try {
server = new ServerSocket(9000, 100);
while (true) {
try {
waitForConnection();
setupStreams();
whileChatting();
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (EOFException e) {
showMessage("\n Connection lost");
} catch (IOException e) {
e.printStackTrace();
} finally {
closeCrap();
}
}
// connect to server
private void waitForConnection() throws IOException {
showMessage(" \nWaiting for connection \n");
connection = server.accept();
showMessage(" now connected to "
+ connection.getInetAddress().getHostName());
}
private void setupStreams() throws IOException {
showMessage("\n Setting up streams \n");
output = new ObjectOutputStream(connection.getOutputStream());
output.flush();
// input = new DataInputStream(connection.getInputStream());
input = new ObjectInputStream(connection.getInputStream());
showMessage(" Streams are good \n");
}
private void whileChatting() throws IOException {
ableToType(true);
String message = "You are now connected ";
sendMessage(message);
do {// have conversation
try {
message = (String) input.readObject();
// message = (String) input.readLine();
showMessage("\n" + message);
} catch (ClassNotFoundException e) {
showMessage("Dont know that object type ");
// TODO: handle exception
}
} while (!message.equals("server - end"));
}
// close everything
private void closeCrap() {
showMessage("\n Closing..");
ableToType(false);
try {
output.close();
input.close();
connection.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// send message to server
private void sendMessage(String message) {
try {
output.writeUTF("CLIENT - " + message);
output.flush();
showMessage("\n" + "CLIENT - " + message);
} catch (IOException e) {
chatWindow.append("\n Smth is wrong sending message");
}
}
private void showMessage(final String m) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
chatWindow.append(m);
}
});
}
private void ableToType(final boolean tof) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
userText.setEditable(tof);
}
});
}
}
And android :
public class MainActivity extends ActionBarActivity {
TextView text;
Socket socket;
DataInputStream is;
ObjectOutputStream os;
public final String TAG = "CLIENT";
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text);
handler = new Handler();
Thread x = new Thread(new ClientThread());
x.start();
handler = new Handler();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//
public class ClientThread implements Runnable {
public ClientThread() {
// TODO Auto-generated constructor stub
}
#Override
public void run() {
// TODO Auto-generated method stub
try {
while (true) {
socket = new Socket("192.168.1.10", 9000);
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Connected.");
try {
os = new ObjectOutputStream(socket.getOutputStream());
} catch (Exception e) {
text.setText("Output stream. smth wrong");
Log.i(TAG, "Output stream. smth wrong");
}
}
});
try {
ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
String line = null;
while ((line = in.readUTF()) != null) {
Log.d("ServerActivity", line);
final String mesg = line;
handler.post(new Runnable() {
#Override
public void run() {
// DO WHATEVER YOU WANT TO THE FRONT END
// THIS IS WHERE YOU CAN BE CREATIVE
text.append(mesg + "\n");
}
});
}
break;
} catch (Exception e) {
handler.post(new Runnable() {
#Override
public void run() {
text.setText("Oops. Connection interrupted. Please reconnect your phones.");
}
});
e.printStackTrace();
}
}
} catch (Exception x) {
}
}
}
}

Android TCP Client TextView doesn't Update

I'm trying to come up with an android client app that talks with a C#server. I want to update my TextView simultaneously with the server reply message. I'm receiving message with this code
public class LogedInActivity extends ActionBarActivity {
private Spinner meterBrands;
private EditText sayacNo,plcNo;
private String serverMessage="Message is";
private TextView serverStatus;
private String messageID="120";
private String messageEnd="*?/";
private Thread clientThread;
private static final int SERVERPORT = sss;
private static final String SERVER_IP = "sss";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loged_in);
serverStatus= (TextView) findViewById(R.id.serverStatus);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void sendMessage(View view) {
hideSoftKeyboard(this);
meterBrands= (Spinner) findViewById(R.id.brandsSpinner);
String temp=String.valueOf(meterBrands.getSelectedItem());
if(isValidMeterAndPLC()){
new Thread(new Runnable() {
public void run() {
connectSocket(messageToSend());
}
}).start();
} else {
new Thread(new Runnable() {
public void run() {
connectSocket("1");
}
}).start();
}
}
private String connectSocket(String message){
String finalText = "";
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
Log.d("TCP", "C: Connecting...");
Socket socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out = null;
BufferedReader in = null;
try {
Log.d("TCP", "C: Sending: '" + message + "'");
out = new PrintWriter( new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())),true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.println(message);
String text = "";
while ((text = in.readLine()) != null) {
finalText += text;
serverStatus.setText(finalText);
}
Log.d("TCP", "C: Sent.");
Log.d("TCP", "C: Done.");
} catch(Exception e) {
Log.e("TCP", "S: Error", e);
} finally {
socket.close();
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: UnknownHostException", e);
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e("TCP", "C: IOException", e);
e.printStackTrace();
}
return finalText;
}
public String messageToSend(){
String infoString;
sayacNo= (EditText) findViewById(R.id.sayacNoTextBox);
plcNo= (EditText) findViewById(R.id.plcNoTextBox);
infoString= messageID+"-"+sayacNo.getText()+"-"+meterBrands.getSelectedItem().toString()+"-"+plcNo.getText()+ "-" +messageEnd+"-" ;
infoString+=checkSum(infoString);
return infoString;
}
public int checkSum(String str){
int checkSum=0;
char [] strChars= str.toCharArray();
for(int i=0;i<strChars.length;i++){
checkSum+= (int) strChars[i];
}
return checkSum;
}
public void messageDisplay(String servermessage){
serverStatus= (TextView) findViewById(R.id.serverStatus);
serverStatus.setText(servermessage);
}
private boolean isValidMeterAndPLC(){
boolean check=true;
int sayacNoInt=0;
sayacNo=(EditText) findViewById(R.id.sayacNoTextBox);
plcNo=(EditText) findViewById(R.id.plcNoTextBox);
sayacNoInt=Integer.parseInt(sayacNo.getText().toString());
if(sayacNoInt<100 || sayacNoInt>65530){
alertbox("Yanlış Sayaç Numarası","Yanlış sayaç numarası girdiniz. Lütfen tekrar deneyin.");
check=false;
}
if(plcNo.getText().toString().length()!=8){
alertbox("Yanlış PLC Numarası","Yanlış PLC numarası girdiniz. Lütfen tekrar deneyin.");
check=false;
}
return check;
}
protected void alertbox(String title, String mymessage)
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
this);
// set title
alertDialogBuilder.setTitle(title);
// set dialog message
alertDialogBuilder
.setMessage(mymessage)
.setCancelable(false)
.setPositiveButton("Okay",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_loged_in,
container, false);
return rootView;
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
hideSoftKeyboard(this);
return false;
}
/*back button override.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
alertbox("asasda","5333434");
return true;
}
return super.onKeyDown(keyCode, event);
}
*/
public static void hideSoftKeyboard(Activity activity) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
}
However, I can't update my TextView since it's in a thread
new Thread(new Runnable() {
public void run() {
connectSocket(messageToSend());
}
}).start();
Simply wrap the sentence where you update with the runOnUiThread() statement. For instance:
your_context.runOnUiThread(new Runnable() {
public void run() {
myTextView.setText("...");
}
});
Anything wrapped in the runOnUiThread() statement will actually be run in the main UI Thread, so be careful to not add some expensive operations here.
---- EDIT ----
new Thread(new Runnable() {
public void run() {
connectSocket(messageToSend());
// Do whatever you need
...
// Once you want to update your TextView...
final myTextView tv = (TextView) your_context.findViewById(R.id.myTextView);
final String myText = "whatever";
your_context.runOnUiThread(new Runnable() {
public void run() {
myTextView.setText(myText);
}
});
}
}).start();

unable to connect wifi socket connection

I have written code for the client and server which will be connected over wifi and client will send string to server, but the problem is even though I think I have implemented the code correctly it doesn't seem to work. Even the logcat is not showing any errors while I run the code on android device. Can someone help please?
Here's the client code.
public class ControlActivity extends Activity {
WifiManager wifi=null;
WifiInfo winfo=null;
Socket ssocket=null;
String sstr=null;
String ipadd=null;
Integer ip;
TextView text;
Integer k=0;
Handler handler;
Boolean pdown=false;
InetAddress seraddr;
public String intToIp(int i) {
return ( i & 0xFF) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ((i >> 24 ) & 0xFF );
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_control);
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
winfo = wifi.getConnectionInfo();
ip = winfo.getIpAddress();
ipadd = intToIp(ip);
try {
seraddr = InetAddress.getByName(ipadd);
} catch (UnknownHostException e) {
e.printStackTrace();
}
text = (TextView)findViewById(R.id.textView1);
text.setText(ipadd);
handler = new Handler(){
#Override
public void handleMessage(Message msg1){
Bundle bundle = msg1.getData();
String str = bundle.getString("key");
text.setText(str);
}
};
ImageButton butup = (ImageButton)findViewById(R.id.buttonup);
butup.setOnTouchListener(new View.OnTouchListener() {
private Thread touchthread;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pdown==false)
pdown=true;
sstr = "up";
this.touchthread = new Thread(new OnTouchClientThread());
this.touchthread.start();
break;
case MotionEvent.ACTION_UP:
pdown=false;
}
return true;
}
});
ImageButton butdown = (ImageButton)findViewById(R.id.buttondown);
butdown.setOnTouchListener(new View.OnTouchListener() {
private Thread touchthread;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
if(pdown==false)
pdown=true;
sstr = "down";
this.touchthread = new Thread(new OnTouchClientThread());
this.touchthread.start();
break;
case MotionEvent.ACTION_UP:
pdown=false;
}
return true;
}
});
}
public class OnTouchClientThread implements Runnable{
#Override
public void run() {
try {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
ssocket = new Socket(seraddr,5479);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ssocket.getOutputStream())),true);
while(pdown==true){
k=k+1;
bundle.putString("key",k.toString());
msg.setData(bundle);
handler.sendMessage(msg);
out.println(sstr);
}
out.flush();
out.close();
ssocket.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
here's the server
public class FInterActivity extends Activity {
WifiManager wifi=null;
Socket ssocket=null;
String sstr=null;
Thread recithrd;
TextView testing;
ServerSocket ss;
Handler handler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_finter);
wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);
testing = (TextView)findViewById(R.id.testtext);
testing.setText("Starting thread");
this.recithrd = new Thread(new ServerThread());
this.recithrd.start();
handler = new Handler(){
#Override
public void handleMessage(Message msg1){
Bundle bundle = msg1.getData();
String str = bundle.getString("key");
testing.setText(str);
}
};
}
public class ServerThread implements Runnable{
#Override
public void run() {
try {
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
ss = new ServerSocket(5479);
ssocket = ss.accept();
while(true){
BufferedReader input = new BufferedReader(new InputStreamReader(ssocket.getInputStream()));
sstr=null;
sstr = input.readLine();
if(sstr!=null){
bundle.putString("key", sstr);
msg.setData(bundle);
handler.sendMessage(msg);
}
}
} catch (UnknownHostException e) {
e.printStackTrace();
handler.post(new Runnable(){
#Override
public void run() {
testing.setText("unknown host");
}
});
} catch (IOException e) {
e.printStackTrace();
handler.post(new Runnable(){
#Override
public void run() {
testing.setText("Io exception");
}
});
}
}
}
and yes i have provided all the permissions required. please help. i am stuck on this for days.
Your code seems to be wrong in more than one place.
1) The client seems to be getting its own address, putting it into seraddr, and trying to connect to itself! Certainly the server has a different address, unless you are doing a local connection and in this case you should just use 127.0.0.1.
2) At server side, you are accept()ing only once, handling the connection and exiting the thread. This means that your server will accept only one connection and no more. Is this what you wanted?

GUI not displaying all packets received

I below is my code for receiving Multicast Wifi Data on android. I am using runnables like below to update the GUI but i found thatsome packets are missing. I am using this code to receive count down message but the count down is not continious. I dont know whether packets are lost due to the style of GUI updating or due to some other problem. request you all to give suggestions.
package com.example.cdttiming;
public class MainActivity extends Activity
{
EditText time;
String s;
Button button;
InetAddress ia = null;
byte[] bmessage = new byte[1500];
DatagramPacket dp = new DatagramPacket(bmessage, bmessage.length);
MulticastSocket ms = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.et_time);
try
{
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
//wm.setWifiEnabled(true);
WifiManager.MulticastLock multicastLock = wm.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
ia = InetAddress.getByName("226.1.1.1");
try {
ms = new MulticastSocket(4321);
} catch (IOException e) {
e.printStackTrace();
}
try {
ms.joinGroup(ia);
} catch (IOException e) {
e.printStackTrace();
}
ms.setReuseAddress(true);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void startProgress(View view) {
Runnable runnable = new Runnable() {
#Override
public void run() {
while(true)
{
try
{
ms.receive(dp);
s = new String(dp.getData(),0,dp.getLength());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
time.post(new Runnable() {
#Override
public void run() {
time.setText(s);
}
});
} // while
}
};
new Thread(runnable).start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
You have no access to main UI thread. That is why you can't set text to UI view element.
There are few methods to get access to UI thread
1) use Activity.runOnUiThread()
this.runOnUiThread( new Runnable() { #Override
public void run() {
time.setText(s);
} })
2) I suppose best in your case use Handler object wich is a bridge between your worker threads and main UI thread
private Handler handler = new Handler(){
#Override
public void handleMessage(Message message) {
switch (message.what) {
case SET_TEXT:{
time.setText(s);
}break;
}
...
handler.sendEmptyMessage(SET_TEXT);

Categories

Resources