Maybe my knowledge about this topic is so small, that the word "callback" is not right here, sorry about that.
If I start an thread in any class/activity/other thread and after finishing I want it to execute some other code from the instance (class/activity/other thread) which started the thread, how do I realize that?
Currently, I do it like this:
Here is pseudocode.
// Method inside class/activity/other thread
private void startThread(){
MyThread thread = new MyThread(this);
thread.start();
}
And inside the Thread
public class MyThread extends Thread{
private (class/activity/other thread) instanceAbove;
public MyThread ( (class/activity/other thread) instanceAbove){
this.instanceAbove = instanceAbove;
}
public void run(){
//Do some stuff
finish();
}
public void finish(){
instanceAbove.MyThreadFinishMethod();
}
}
I think this is not a good way, but can you give me an example?
Using interfaces is working for AlertDialog
s, because I can use onAppend()
. However, in this case, I don't know how I could use them.
You can easily use an interface
and handle the callback accordingly from your calling activity/class/other thread. Here is an example.
Define an interface like the following first.
public interface ThreadFinishListener {
void onFinish();
}
Let us assume you are instantiating a Thread
from an Activity
. Hence implement the listener in your Activity
like the following.
public class MainActivity extends AppCompatActivity implements ThreadFinishListener {
// .... Other functions in your activity
@Override
void onFinish() {
// Do something when the Thread is finished and returned back to the activity
// This is actually your callback function.
}
}
Now modify the constructor of your Thread
class so that you can pass the listener to it.
public class MyThread extends Thread {
private ThreadFinishListener listener;
public MyThread(ThreadFinishListener listener){
this.listener = listener;
}
public void run(){
//Do some stuff
finish();
}
public void finish() {
// This will invoke the function call in your activity
listener.onFinish();
}
}
Now while initializing your Thread
, you might want to pass the listener to it as follows.
MyThread thread = new MyThread(this);
thread.run();
I hope that suffices.