I have my UI and other Thread, where there is loop:
while(true){
}
I am checking changes of String value in the system, and when changes, I send message via pre-opened socket to the server. Problem is, when applying loop, my app freezes, and CPU load is very high (about 90 %). I know, infinite loop must not be done in thread, but do you know how to copy this behavior, not using infinite loop?
Thx
Main Code (onCreate method):
mProgressDialog = ProgressDialog.show(main.this, "loading","loading", true);
c=new Client(this.getApplicationContext(), "192.168.0.121", 3333);
c.start();
CLIENT_MESSAGE="login user2 user2";
synchronized(c){
c.notify();
}
Client.zHandler.setEmptyMessage(119);
mHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 11:
Log.d("Logged in", "login");
mProgressDialog.dismiss();
break;
case 12:
Log.d("Logged out", "logout and end");
mProgressDialog.dismiss();
finish();
break;
}
}
};
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
CLIENT_MESSAGE="logout";
synchronized (c) {
c.notify();
}
Client.zHandler.setEmptyMessage(129)
break;
default:
}
return true;
}
Thread Code (Client.java):
public Client(Context ctx, String hostname, int port){
this.ctx=ctx;
this.hostname=hostname;
this.port=port;
zHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case 119://login
Log.d("119", "case 119");
messageText=DropboxFileClientActivity.CLIENT_MESSAGE;
main.mHandler.sendEmptyMessage(11);
break;
case 129://logout
messageText=DropboxFileClientActivity.CLIENT_MESSAGE;
main.mHandler.sendEmptyMessage(12);
break;
case 100:
break;
}
}
};
}
public void run(){
try {
clientSocket = new Socket(hostname, port);
//inputLine = new BufferedReader(new InputStreamReader(System.in));
os = new ObjectOutputStream (clientSocket.getOutputStream());
is = new ObjectInputStream(clientSocket.getInputStream());
}
catch (UnknownHostException e) {
Log.d("ERROR", "unknown host "+hostname);
}
catch (IOException e) {
Log.d("ERROR2", "no bind"+hostname);
e.printStackTrace();
}
while (!isInterrupted()) {
try{
synchronized (this) {
wait();
}
} catch (InterruptedException e) {
break; // interrupting the thread ends it
}
if (clientSocket != null && os != null && is != null &&!messageText.equals("")) {
messageText="";
//sending message to server, getting reply and displaying it to the screen
}
}//endwhile loop
}