I have got this code that connect to a server and send message, it works perfectly, I just don't get the idea of runnable. Is the code within the run(){ } is executed in a loop? I tried puttin a log.e inside, and it only prints once, so how does it actually work?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
Log.e("in try","run");
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
Is the code within the run(){ } is executed in a loop?
Note: You can use other ways to call it in a loop like handler can post it again to the handler with the call to - handler.postDelayed(this, 1000);
every 1000 ms
.
Represents a command that can be executed. Often used to run code in a different Thread.
Public Methods:
public abstract void run ()
Starts executing the active part of the class' code. This method is called when a thread is started that has been created with a class which implements Runnable.
Basics of Runnable -
Using Runnable
Interface, you can run the class several times.
Example -
class ClientThread implements Runnable {
@Override
public void run() {
Log.e("in try","run");
//Some code
}
}
//Multiple threads share the same object.
ClientThread rc = new ClientThread ();
Thread t1 = new Thread(rc);
t1.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t2 = new Thread(rc);
t2.start();
Thread.sleep(1000); // Waiting for 1 second before starting next thread
Thread t3 = new Thread(rc);
t3.start();
Reference: Runnable in Android.